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;
usin开发者_高级运维g 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.
Update you 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>
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.
Add a using
clause for 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.
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:
Html.MyMenu()
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
<%@ Import Namespace="MvcApplication1.HelperMethods" %>
精彩评论