【问题标题】:Using a HtmlHelper in MVC 5在 MVC 5 中使用 HtmlHelper
【发布时间】:2015-01-14 01:09:46
【问题描述】:

我正在编写一个MVC 5 互联网应用程序,我希望在view 中使用DisplayFor 方法时显示divId

这是我的一些代码:

public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
{
    var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
    return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}</{0}>", wrapperTag, id, helper.DisplayFor(expression)));
}

这是我得到的错误:

'System.Web.Mvc.HtmlHelper' 不包含对 'DisplayFor' 并且没有扩展方法 'DisplayFor' 接受第一个 可以找到“System.Web.Mvc.HtmlHelper”类型的参数 (您是否缺少 using 指令或程序集引用?)

我不确定我是否将DisplayWithIdFor 方法放在了正确的位置。我希望在名为AssetControllercontrollerEdit view 中使用DisplayWithIdFor 方法,并将DisplayWithIdFor 方法放在AssetController 中。

我可以就这段代码寻求帮助吗?

提前致谢。

【问题讨论】:

    标签: asp.net-mvc-5 html-helper asp.net-mvc-views displayfor


    【解决方案1】:

    你的方法应该是这样的

    using System;
    using System.Linq.Expressions;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    namespace YourAssembly.Html
    {
      public static class DisplayHelper
      {
        public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
        {
          var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
          MvcHtmlString text = DisplayExtensions.DisplayFor(helper, expression);
          Tagbuilder html = new TagBuilder(wrapperTag);
          html.MergeAttribute("id", id);
          html.InnerText = text;
          return MvcHtmlString.Create(html.ToString());
        }
      }
    }
    

    【讨论】:

    • 我已经按照你的建议做了,但是使用@Html 时找不到DisplayWithIdFor。语法。
    • 您是否在视图中包含了对它的引用? @using YourAssembly.Html;?或者,如果您还想在其他视图中使用它,请将其添加到 web.config
    • 请注意,您可以通过删除var id = ... 行并将html.MergeAttribute("id", id) 替换为html.GenerateId(ExpressionHelper.GetExpressionText(expression)); 来简化这一点
    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2010-11-23
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多