本文介绍了创建/ MVC中控制器获取DefaultHtmlGenerator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建(或某种方式得到它的一个实例),用于Microsoft.AspNet.Mvc.Rendering.DefaultHtmlGenerator我MVC6控制器的方法在

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

我想生成验证HTML我型我我的asp.net MVC的控制器内部的自我。我的问题是从哪里得到的构造数据DefaultHtmlGenerator像防伪,metadataProvider..etc

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)
}

下面是一个关于HtmlGenerator类链接
DefaultHtmlGenerator

here is the a link about the HtmlGenerator classDefaultHtmlGenerator

推荐答案

由于MVC 6是基于依赖注入,所有你需要做的就是要求 IHtmlGenerator 在构造函数和DI容器将自动填写所有的依赖 DefaultHtmlGenerator (前提是什么,是建立在你的DI配置)。

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();
    }
}

不过,现在看来, GetClientValidationRules 方法仅设计到一个视图中工作,因为它接受 ViewContext 作为参数。但这并回答你问的问题。

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.

这篇关于创建/ MVC中控制器获取DefaultHtmlGenerator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-06 11:59