Create/Get DefaultHtmlGenerator from MVC Controller

余生颓废 提交于 2019-12-02 03:39:50

问题


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 generate the html for validation for my Model my self inside my controller of asp.net mvc. My issue is where to get the constructor data for DefaultHtmlGenerator like antiforgery, metadataProvider..etc

 [HttpGet]
 public IActionResult GetMarkup()
 {
    // IHtmlGenerator ge = this.CurrentGenerator(); 
    IHtmlGenerator ge = new DefaultHtmlGenerator(params);
    var tag= ge.GetClientValidationRules(params)
}

here is the a link about the HtmlGenerator class DefaultHtmlGenerator


回答1:


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.



来源:https://stackoverflow.com/questions/34620322/create-get-defaulthtmlgenerator-from-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!