Asp.net mvc 5 在MVC5中使用HtmlHelper
我正在编写一个MVC5 internet应用程序,我希望在视图中使用DisplayFor方法时显示div的Id 以下是我的一些代码:Asp.net mvc 5 在MVC5中使用HtmlHelper,asp.net-mvc-5,html-helper,asp.net-mvc-views,displayfor,Asp.net Mvc 5,Html Helper,Asp.net Mvc Views,Displayfor,我正在编写一个MVC5 internet应用程序,我希望在视图中使用DisplayFor方法时显示div的Id 以下是我的一些代码: public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "
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方法放置在正确的位置。我希望在名为AssetController的控制器的编辑视图中使用DisplayWithIdFor方法,并已将DisplayWithIdFor方法放置在AssetController中
我可以在这个代码上得到一些帮助吗
提前感谢。您的方法应该是
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。语法。您是否在视图中包含对它的引用@使用YourAssembly.Html;?或者,如果您还想在其他视图中使用它,请将其添加到web.config.Note您可以通过删除var id=。。。行并将html.MergeAttributeid,id替换为html.generateIdeExpressionHelper.GetExpressionTextexpression;