使用创建的扩展方法
这是我创建的方法:
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 关键字在我的视图中使用此扩展方法(现在,我正在使用 _layout.cshtml),如下所示:
@Html.MyMenu //doesn't appears to be in the available method selection.
我不能这样做的原因是什么像这样调用这个方法?感谢您的帮助。
Here's the method I created:
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();
}
}
}
I was told that I could then use this extension method in my Views (right now, I'm using _layout.cshtml) by using the @Html keyword, like so:
@Html.MyMenu //doesn't appears to be in the available method selection.
What's the reason why I can't call this method like that? Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新您的 web.config:
这样您就不需要在每个视图中使用 MvcApplicatin1.HelperMethods 的 using 指令。您可以在该命名空间中放置多个辅助类。
Update you web.config:
This way you won't need to use the using directive for MvcApplicatin1.HelperMethods in each View. And you can put multiple helper classes in that namespace.
为
MvcApplication1.HelperMethods
添加using
子句Add a
using
clause forMvcApplication1.HelperMethods
如果没有看到您的视图代码,很难准确地说,但您可能在视图代码中缺少对 MvcApplication1.HelperMethods 的引用。
Wihtout seeing your view code it is hard to say exactly but you are probably missing a reference to MvcApplication1.HelperMethods in the view code.
您不需要
@
,Html
应该就可以了(尽管@Html
也应该可以工作)。不过,您需要实际调用该方法:如果您没有像 ReSharper 这样的程序来为您提供建议,则需要包含对该命名空间的引用
You shouldn't need the
@
,Html
should do just fine (though@Html
should work as well). You'd need to actually invoke the method, though:And if you haven't got a program like ReSharper that'll suggest this for you, you need to include a reference to that namespace