c# - 使用创建的扩展方法

标签 c# view extension-methods

这是我创建的方法:

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/

相关文章:

c# - 将 DateTimePicker 绑定(bind)到 UTC,但以本地时间显示和操作

android 如何在布局开始时添加 View ?

android - 如何为自定义 Android 通知向 RemoteView 添加垂直线?

c# - 在没有显式引用的情况下调用方法的扩展方法

c# - 支持异步操作的自定义线程池

c# - 有什么充分的理由不依赖业务逻辑中的数据库 key 完整性吗?

c# - 单击子控件时如何处理控件上的 Click 事件?

python - 如何从网络浏览器中运行我的 python 脚本并处理结果?

c# - 如何在 C# 中扩展返回泛型值的泛型类?

Android:将 .extensions 转换为小写/大写