C# Net MVC使用变量调用HtmlHelper
我使用HtmlHelper(在Asp.NETMVC4.5中)为每个类属性创建多个验证字段。现在,我需要依次给他们打电话C# Net MVC使用变量调用HtmlHelper,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我使用HtmlHelper(在Asp.NETMVC4.5中)为每个类属性创建多个验证字段。现在,我需要依次给他们打电话 @Html.LabelFor(m => m.SomeField) @Html.EditorFor(m => m.SomeField) @Html.ValidationMessageFor(m => m.SomeField) 因此,我更愿意将“m=>m.SomeField”传递给ViewHelper,并使其类似于这样 @helper FieldHelper([
@Html.LabelFor(m => m.SomeField)
@Html.EditorFor(m => m.SomeField)
@Html.ValidationMessageFor(m => m.SomeField)
因此,我更愿意将“m=>m.SomeField”传递给ViewHelper,并使其类似于这样
@helper FieldHelper([???] ValueINeed)
{
@Html.LabelFor(ValueINeed)
@Html.EditorFor(ValueINeed)
@Html.ValidationMessageFor(ValueINeed)
}
// And then call the helper with...
ViewHelper.FieldHelper(m => m.SomeField)
我的问题是:这可能吗?变量是什么类型的?微软文档说它是“表达式”,但我还没能构造出这样一个有值的对象。提前感谢大家。我认为您无法使用助手来完成此操作,我很确定您将不得不创建一个扩展方法:
public static MvcHtmlString FieldHelper<TModel, TItem>(this HtmlHelper<TModel> html, Expression<Func<TModel, TItem>> expr)
{
var output = html.LabelFor(expr);
output += html.EditorFor(expr);
output += html.ValidationMessageFor(expr);
return MvcHtmlString.Create(output);
}
publicstaticmvchtmlstringfieldhelper(这个htmlhelperhtml,表达式expr)
{
var output=html.LabelFor(expr);
output+=html.EditorFor(expr);
output+=html.ValidationMessageFor(expr);
返回MvcHtmlString.Create(输出);
}
然后,在您看来:
@Html.FieldHelper(x=>x.SomeField)
那么,添加这个额外的抽象层有什么好处呢ViewHelper.FieldHelper
有更多的字符,因此您获得了什么?使查看代码更容易浏览。另外,助手的功能没有在这里展示,主要是为公司品牌的UI提供布局。@Codingyosi我注意到我忘记了示例中的另外两个字段,很抱歉造成混淆。我会通过扩展名(如Html.LabelCustomFor
)来完成,并复制Html.LabelFor
的签名。在这个新方法中添加您的自定义内容。我记得以前尝试过类似的方法,但出于某种原因,“…不包含LabelFor的定义”(等)问题总是会出现。使用语句时很可能缺少:使用System.Web.Mvc;使用System.Web.Mvc.Html你说得对,我确实忘记了一个要点。非常感谢,这个建议奏效了!