与 Razor 一起使用时,我在使用 Html Helpers 时遇到困难。上述助手在带有 Web 表单 View 引擎的 MVC 2 中工作得很好。但不是用 Razor 。我在运行时遇到的错误是:
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)
展开“显示详细编译器输出”显示:
d:\...\Views\Shared\MenuTop.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:\...\Views\Shared\MenuTop.cshtml(2,7): error CS1503: Argument 1: cannot convert from 'void' to 'System.Web.WebPages.HelperResult'
这向我表明,razor 不喜欢我的助手 IncrementalMenu,返回 void(在 MVC 2 Web 表单引擎 View 中工作正常)。
尽管代码行 (@Html.IncrementalMenu(...)) 带有红色下划线并带有以下消息,但我在编译时没有收到任何错误:
Cannot implicitly convert type 'void' to 'object'
IncrementalMenu 位于 Wingspan.Web.Mvc 命名空间中。其签名如下:
public static void IncrementalMenu(this HtmlHelper html, MenuBlock menuBlock)
{
// Uses an HtmlTextWriter to render a menu from the sitemap
}
如果我知道出了什么问题,我会很震惊......
附注:
MenuBlock 参数只是一个枚举,用于标识菜单应如何呈现。不要专注于此,因为那很好。
最佳答案
你可以这样调用你的助手:
@{ Html.IncrementalMenu(MenuBlock.Site); }
WebForms 语法
<% Html.IncrementalMenu(MenuBlock.Site); %>
您只需调用您的方法,并且返回值(如果有)将被忽略。
这样的代码需要一个返回值,并将返回值写入 html 流:
@Html.YourHelper()
网络表单语法:
<%: Html.YourHelper() %>
相同,如果结果值!= IHtmlString:
<%= Server.HtmlEncode(Html.YourHelper()) %>
关于asp.net-mvc - ASP.NET MVC : Custom Html Helpers in Razor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4216736/