Using HtmlHelper in a Controller

后端 未结 7 1454
悲哀的现实
悲哀的现实 2020-11-27 04:34

Is it possible to use HtmlHelper in a controller, for-example to get the TextBox(...) method? not that I can\'t write the html that it generates myself, but I just want to u

7条回答
  •  执笔经年
    2020-11-27 05:12

    For .NET Core 2 MVC: https://github.com/aspnet/Mvc/issues/7321

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Infrastructure;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.Routing;
    using Microsoft.AspNetCore.Mvc.ViewEngines;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
    using Microsoft.Extensions.Options;
    using System.IO;
    using System.Text.Encodings.Web;
    using System.Threading.Tasks;
    
    
        public class HelperGenerator
        {
            private readonly IHtmlGenerator _htmlGenerator;
            private readonly ICompositeViewEngine _compositeViewEngine;
            private readonly IModelMetadataProvider _modelMetadataProvider;
            private readonly IViewBufferScope _viewBufferScope;
            private readonly IActionContextAccessor _actionContextAccessor;
            private readonly HtmlHelperOptions _htmlHelperOptions;
    
            public HelperGenerator(IHtmlGenerator htmlGenerator, ICompositeViewEngine compositeViewEngine, IModelMetadataProvider modelMetadataProvider, IViewBufferScope viewBufferScope, IActionContextAccessor actionContextAccessor, IOptions options)
            {
                _htmlGenerator = htmlGenerator;
                _compositeViewEngine = compositeViewEngine;
                _modelMetadataProvider = modelMetadataProvider;
                _viewBufferScope = viewBufferScope;
                _actionContextAccessor = actionContextAccessor;
                _htmlHelperOptions = options.Value.HtmlHelperOptions;
            }
            public IHtmlHelper HtmlHelper(ViewDataDictionary ViewData, ITempDataDictionary TempData)
            {
                var helper = new HtmlHelper(_htmlGenerator, _compositeViewEngine, _modelMetadataProvider, _viewBufferScope, HtmlEncoder.Default, UrlEncoder.Default);
                var viewContext = new ViewContext(_actionContextAccessor.ActionContext,
                   new FakeView(),
                   ViewData,
                   TempData,
                   TextWriter.Null,
                   _htmlHelperOptions);
                helper.Contextualize(viewContext);
                return helper;
            }
            private class FakeView : IView
            {
                public string Path => "View";
    
                public Task RenderAsync(ViewContext context)
                {
                    return Task.FromResult(0);
                }
            }
        }
    

    Make sure to register in services:

    services.AddSingleton();
    

提交回复
热议问题