之前使用wtm来进行快速开发
(相关资料图)
wtm框架见:
https://wtmdoc.walkingtec.cn/
其前端选择Layui的情况下有大量的TagHelper,大幅度提高了开发效率
虽然已有的组件很丰富但也不能完全覆盖所有的需求,这个时候就需要自己写TagHelper。
参考了WTM源码,和微软官方文档
TagHelper虽然使用起来方便,但是大量的拼接字符串编写体验和可读性都不是很好。
理想的情况是能充分利用.net中强大的Razor引擎来编写TagHelper,从而更方便的进行组件复用。
可以从asp.net core中找到viewengine的使用方法
以封装一个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视图引擎编写可读性就好了很多。
@using TagHelpers;@model WangEditorConfig
关键词: