是否可以从类中访问Html而不作为参数发送?

时间:2011-05-09 13:28:20

标签: c# asp.net-mvc-3 html-helper

我想访问一个类中的Html对象,因此我可以使用Class.Method调用Html.Partial来呈现内容。

有没有办法可以称之为Class.Method()而不是Class.Method(Html)

1 个答案:

答案 0 :(得分:1)

您可能需要引用HtmlHelper来调用Partial方法。

您可以将其作为HtmlHelper

的扩展名
public static MvcHtmlString Method(this HtmlHelper helper, Class @class)
{
    return helper.Partial(....);
}

或者在HtmlHelper上的Method方法中创建一个Class,这可能会更成问题,因为除非您通过它找到对该类的引用,否则该类将不存在你的HttpContext

您可以在控制器上轻松创建HtmlHelper,如下所示:

    HtmlHelper _htmlHelper;
    public HtmlHelper HtmlHelper
    {
        get 
        {
            if (_htmlHelper == null)
            {
                TextWriter writer = new StringWriter();
                _htmlHelper = new HtmlHelper(new ViewContext(ControllerContext,
                    new WebFormView("Default"),
                    new ViewDataDictionary(),
                    new TempDataDictionary(), writer), new ViewPage());
            }

            return _htmlHelper;
        }
    }