Here is the complete solution for what you are looking for. I used dependency injection to get the HtmlHelper in the controller. You can also add your own assistant if you wish.
using Microsoft.AspNet.Html.Abstractions; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.ModelBinding; using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNet.Mvc.ViewEngines; using Microsoft.AspNet.Mvc.ViewFeatures; using Microsoft.AspNet.Mvc.ViewFeatures.Internal; using Microsoft.Extensions.WebEncoders; using System.ComponentModel.DataAnnotations; using System; public class MyController : Controller { private readonly IHtmlGenerator htmlGenerator; ICompositeViewEngine viewEngine; IModelMetadataProvider metadataProvider; private readonly IHtmlHelper helper; IHtmlEncoder htmlEncoder; IUrlEncoder urlEncoder; IJavaScriptStringEncoder javaScriptStringEncoder; public MyController(IHtmlHelper helper, IHtmlGenerator htmlGenerator, ICompositeViewEngine viewEngine, IModelMetadataProvider metadataProvider, IHtmlEncoder htmlEncoder, IUrlEncoder urlEncoder, IJavaScriptStringEncoder javaScriptStringEncoder) { this.htmlGenerator = htmlGenerator; this.viewEngine = viewEngine; this.metadataProvider = metadataProvider; this.htmlEncoder = htmlEncoder; this.urlEncoder = urlEncoder; this.javaScriptStringEncoder = javaScriptStringEncoder; this.helper = helper; } [HttpGet] public IActionResult MyHtmlGenerator() { MyViewModel temp = new MyViewModel(); var options = new HtmlHelperOptions(); options.ClientValidationEnabled = true; ViewDataDictionary<MyViewModel> dic = new ViewDataDictionary<MyViewModel>(this.metadataProvider, new ModelStateDictionary()); ViewContext cc = new ViewContext(ActionContext, new FakeView(), dic, TempData, TextWriter.Null, options); var type = typeof(MyViewModel); var metadata = this.metadataProvider.GetMetadataForType(type); ModelExplorer modelEx = new ModelExplorer(this.metadataProvider, metadata, temp); ViewData["Description"] = "test desc"; ViewData["Id"] = 1; this.ViewData = new ViewDataDictionary(this.metadataProvider, new ModelStateDictionary()); IHtmlHelper<MyViewModel> dd = new HtmlHelper<MyViewModel>(this.htmlGenerator, this.viewEngine, this.metadataProvider, this.htmlEncoder, this.urlEncoder, this.javaScriptStringEncoder); ((ICanHasViewContext)dd).Contextualize(cc); dd.ViewContext.ViewData = this.ViewData; var desc = GetString(dd.TextBoxFor(m => m.ID)); var ID = GetString(dd.TextBoxFor(m => m.Description));
source share