3

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

Helen Araya
  • 1,886
  • 3
  • 28
  • 54
  • Link is dead :( here's the MSDN page: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.viewfeatures.defaulthtmlgenerator?view=aspnetcore-2.2 – chakeda Feb 07 '19 at 21:26

1 Answers1

3

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.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • 1
    Thanks. This is related question. How can I generate( the markup from model using this(IHtmlGenerator) class? Or do I have to use another class. I don't have a knowledge of the view.html. I wanted to generate a validation html from the model validation attrubutes. – Helen Araya Jan 05 '16 at 23:11
  • @AmeteBlessed Did you find an answer for this? I also want to generate the validation html. – Haytam Sep 07 '18 at 09:50
  • @Haytam look at my answer in [Here](https://stackoverflow.com/a/34955964/3038042) please upvote it if you are satisfied with my answer. – Helen Araya Sep 07 '18 at 22:45