Create/Get DefaultHtmlGenerator from MVC Controller

前端 未结 1 1900
刺人心
刺人心 2021-01-20 19:43

I am trying to create(Or get an instance of it somehow) for Microsoft.AspNet.Mvc.Rendering.DefaultHtmlGenerator inside my MVC6 controller method

I wanted to generat

1条回答
  •  伪装坚强ぢ
    2021-01-20 20:04

    Since MVC 6 is based on dependency injection, all you have to do is require IHtmlGenerator in your constructor, and the DI container will automatically fill in all of the dependencies of DefaultHtmlGenerator (provided that is what is setup in your DI configuration).

    public class HomeController : Controller
    {
        private readonly IHtmlGenerator htmlGenerator;
    
        public HomeController(IHtmlGenerator htmlGenerator)
        {
            if (htmlGenerator == null)
                throw new ArgumentNullException("htmlGenerator");
            this.htmlGenerator = htmlGenerator;
        }
    
        public IActionResult GetMarkup()
        {
            // Use the HtmlGenerator as required.
            var tag = this.htmlGenerator.GetClientValidationRules(params);
    
            return View();
        }
    }
    

    That said, it appears that the GetClientValidationRules method is only designed to work within a view, since it accepts ViewContext as a parameter. But this does answer the question that you asked.

    0 讨论(0)
提交回复
热议问题