之前使用wtm來(lái)進(jìn)行快速開(kāi)發(fā)
(相關(guān)資料圖)
wtm框架見(jiàn):
https://wtmdoc.walkingtec.cn/
其前端選擇Layui的情況下有大量的TagHelper,大幅度提高了開(kāi)發(fā)效率
雖然已有的組件很豐富但也不能完全覆蓋所有的需求,這個(gè)時(shí)候就需要自己寫(xiě)TagHelper。
參考了WTM源碼,和微軟官方文檔
TagHelper雖然使用起來(lái)方便,但是大量的拼接字符串編寫(xiě)體驗(yàn)和可讀性都不是很好。
理想的情況是能充分利用.net中強(qiáng)大的Razor引擎來(lái)編寫(xiě)TagHelper,從而更方便的進(jìn)行組件復(fù)用。
可以從asp.net core中找到viewengine的使用方法
以封裝一個(gè)wangEditor為例
TagHelper:
using Microsoft.AspNetCore.Html;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc.ModelBinding;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewEngines;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;using System;using System.IO;using WalkingTec.Mvvm.Core;using WalkingTec.Mvvm.Core.Extensions;using WalkingTec.Mvvm.TagHelpers.LayUI;namespace TagHelpers{ [HtmlTargetElement("wt:wangeditor", Attributes = "field", TagStructure = TagStructure.WithoutEndTag)] public class WangEditorTagHelper : TagHelper { public WangEditorTagHelper(ICompositeViewEngine viewEngine,IHttpContextAccessor httpContextAccessor) { _viewEngine = viewEngine; _httpContextAccessor = httpContextAccessor; } public ModelExpression Field { get; set; } public string Id { get; set; } public string Name { get; set; } public int Height { get; set; } = 300; private ICompositeViewEngine _viewEngine; private IHttpContextAccessor _httpContextAccessor; public override void Process(TagHelperContext context, TagHelperOutput output) { var viewEngineResult = _viewEngine.GetView("~/Views/Shared/Components/WangEditor/", "Default.cshtml", false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn"t find view /Shared/Components/WangEditor/Default.cshtml"); } using (var sr = new StringWriter()) { var viewContext = new ViewContext(); viewContext.HttpContext = _httpContextAccessor.HttpContext; viewContext.ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = new WangEditorConfig() { Id = Id ?? Utils.GetIdByName(Field?.ModelExplorer.Container.ModelType.Name + "." + Field?.Name), Name = Name ?? Field?.Name, Value = Field?.Model?.ToString(), Height = Height } }; viewContext.Writer = sr; viewEngineResult.View.RenderAsync(viewContext).GetAwaiter().GetResult(); output.TagName = "div"; output.TagMode = TagMode.StartTagAndEndTag; output.Content.SetHtmlContent(sr.ToString()); } } } public class WangEditorConfig { public string Id { get; set; } public string Name { get; set; } public string Value { get; set; } public int Height { get; set; } }}
cshtml,使用razor視圖引擎編寫(xiě)可讀性就好了很多。
@using TagHelpers;@model WangEditorConfig
關(guān)鍵詞: