ASP.NET MVC:Razor 中的自定义 Html Helpers [英] ASP.NET MVC: Custom Html Helpers in Razor
问题描述
与 Razor 一起使用时,我在使用 Html Helpers 时遇到困难.所述助手在带有 Web 表单视图引擎的 MVC 2 中运行良好.但不是在剃刀里.我在运行时得到的错误是:
I am having difficulty with Html Helpers when used with Razor. Said helpers worked fine in MVC 2 with the web form view engine. But not in razor. The error I get at runtime is:
Compiler Error Message: CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
Source Error:
Line 1: @using Wingspan.Web.Mvc;
Line 2: @Html.IncrementalMenu(MenuBlock.Site)
展开显示详细的编译器输出显示:
Expanding the Show Detailed Compiler Output reveals:
d:...ViewsSharedMenuTop.cshtml(2,1): error CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
d:...ViewsSharedMenuTop.cshtml(2,7): error CS1503: Argument 1: cannot convert from 'void' to 'System.Web.WebPages.HelperResult'
这向我表明 razor 不喜欢我的助手 IncrementalMenu 返回 void(在 MVC 2 Web 表单引擎视图中工作正常).
That indicates to me that razor doesn't like my helper, IncrementalMenu, returning void (which works fine in MVC 2 web form engine views).
我在编译时没有遇到错误,尽管代码行 (@Html.IncrementalMenu(...)) 是红色下划线并带有以下消息:
I get no errors at Compile time, although the line of code (@Html.IncrementalMenu(...)) is red underlined with the following message:
Cannot implicitly convert type 'void' to 'object'
IncrementalMenu 位于 Wingspan.Web.Mvc 命名空间中.其签名如下:
IncrementalMenu is in the Wingspan.Web.Mvc namespace. It's signature is as follows:
public static void IncrementalMenu(this HtmlHelper html, MenuBlock menuBlock)
{
// Uses an HtmlTextWriter to render a menu from the sitemap
}
如果我知道出了什么问题,我会很生气...
I'm blowed if I know what is wrong...
附注:
MenuBlock 参数只是一个枚举,用于标识菜单应如何呈现.不要专注于此,因为那很好.
The MenuBlock parameter is just an enum that identifies how the menu should render. Don't fixate on this as that is fine.
推荐答案
你可以这样调用你的助手:
You can call your helper like this:
@{ Html.IncrementalMenu(MenuBlock.Site); }
WebForms 语法
WebForms syntax
<% Html.IncrementalMenu(MenuBlock.Site); %>
您只需调用您的方法,返回值(如果有)将被忽略.
You just call your method, and the return value (if there is any) is ignored.
像这样的代码需要一个返回值,并将返回值写入 html 流:
Code like this expects a return value, and writes the return value to the html stream:
@Html.YourHelper()
网络表单语法:
<%: Html.YourHelper() %>
相同,如果结果值 != IHtmlString:
The same, if result value != IHtmlString:
<%= Server.HtmlEncode(Html.YourHelper()) %>
这篇关于ASP.NET MVC:Razor 中的自定义 Html Helpers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!