Create Custom HTML Helper in ASP.Net Core

前端 未结 7 1372
南笙
南笙 2020-12-28 13:10

I want to create my own custom HTML Helper like the ones used in ASP.NET MVC, but I haven\'t been able to find how to implement them in the correct way.

I have found

7条回答
  •  孤独总比滥情好
    2020-12-28 13:42

    Well i guess this answer won't be noticed but here's what i came up with using service registrations:

    I hope it helps someone.

    Register the service:

    services.AddTransient();
    

    Use the service:

    var helper = HttpContext.RequestServices.GetRequiredService().Create();
    

    Interface:

    public interface IHtmlHelperFactory
    {
        IHtmlHelper Create();
    }
    

    Implementation:

    public class HtmlHelperFactory : IHtmlHelperFactory
    {
        private readonly IHttpContextAccessor _contextAccessor;
    
        public class FakeView : IView
        {
            /// 
            public Task RenderAsync(ViewContext context)
            {
                return Task.CompletedTask;
            }
    
            /// 
            public string Path { get; } = "View";
        }
    
        public HtmlHelperFactory(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
    
        /// 
        public IHtmlHelper Create()
        {
            var modelMetadataProvider = _contextAccessor.HttpContext.RequestServices.GetRequiredService();
            var tempDataProvider = _contextAccessor.HttpContext.RequestServices.GetRequiredService();
            var htmlHelper = _contextAccessor.HttpContext.RequestServices.GetRequiredService();
            var viewContext = new ViewContext(
                new ActionContext(_contextAccessor.HttpContext, _contextAccessor.HttpContext.GetRouteData(), new ControllerActionDescriptor()),
                new FakeView(),
                new ViewDataDictionary(modelMetadataProvider, new ModelStateDictionary()),
                new TempDataDictionary(_contextAccessor.HttpContext, tempDataProvider),
                TextWriter.Null,
                new HtmlHelperOptions()
            );
    
            ((IViewContextAware)htmlHelper).Contextualize(viewContext);
            return htmlHelper;
        }
    }
    

提交回复
热议问题