Using html helpers in Razor web helper

2020-02-26 06:05发布

I am trying to create a Razor web helper something like this :

@helper DisplayForm() {    
    @Html.EditorForModel();    
}

But this gives the error "CS0103: The name 'Html' does not exist in the current context".

Is there any way to reference html helpers within web helpers?

3条回答
爷、活的狠高调
2楼-- · 2020-02-26 06:39

Razor inline WebHelper is generate static method.

So can not access instance member.

@helper DisplayForm(HtmlHelper html){
    @html.DisplayForModel()
}

How about this?

查看更多
孤傲高冷的网名
3楼-- · 2020-02-26 06:43

Declarative helpers in Razor are static methods. You could pass the Html helper as argument:

@helper DisplayForm(HtmlHelper html) {
    @html.EditorForModel(); 
}

@DisplayForm(Html)
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-26 06:56

You can cast the static Page property from the context to the correct type:

@helper MyHelper() {
    var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;

    Html.RenderPartial("WhatEver");
    @Html.EditorForModel();
}
查看更多
登录 后发表回答