这是我创建的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcApplication1.Models;
using System.Text;
namespace MvcApplication1.HelperMethods
{
public static class NavigationalMenu
{
public static string MyMenu(this HtmlHelper helper)
{
ProyectoFinalEntities x = new ProyectoFinalEntities();
var categories = x.Categories;
StringBuilder stringBuilder = new StringBuilder();
foreach (Category c in categories)
{
stringBuilder.Append(helper.RouteLink(c.Name, "AuctionCategoryDetails", new { categoryName = c.Name }).ToString());
}
return stringBuilder.ToString();
}
}
}
有人告诉我,我可以通过使用 @Html 关键字在我的 View 中使用此扩展方法(现在,我正在使用 _layout.cshtml),如下所示:
@Html.MyMenu //doesn't appears to be in the available method selection.
为什么我不能这样调用这个方法?感谢您的帮助。
最佳答案
更新你的 web.config:
<system.web>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="System.Web.Helpers" />
...
<add namespace="MvcApplication1.HelperMethods" /><!-- Add this line -->
</namespaces>
</pages>
</system.web>
这样您就不需要在每个 View 中使用 MvcApplicatin1.HelperMethods 的 using 指令。您可以在该命名空间中放置多个辅助类。
关于c# - 使用创建的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4439271/