MVC3 扩展方法 .
本文关键字:TValue TModel 扩展 方法 MVC3 | 更新日期: 2023-09-27 18:32:25
>编辑:感谢David Ruttka,我在查看了Mvc3的RTM版本中的LabelExtensions.cs后才弄清楚。
对于字段名称:字符串字段 = ExpressionHelper.GetExpressionText(expression);
对于模型,我需要指定要为助手铸造的模型-其中 TModel:Foo然后我可以得到模型:BarTypeEnum barType = ((Foo)html.视图数据模型)。条形类型;
我已经将下面的来源更新为对我有用的内容。
/编辑
我正在尝试创建一个类似于 Mvc3 中的 LabelFor 的 html 帮助程序函数,以返回基于 Foo.BarType 和从 html 传入的 Foo 字段名称的字符串值。
在下面的函数 FooLabelFor 中,如何将模型和字段名称传递到函数中?
我去寻找System.Web.Mvc.HtmlLabelFor的源代码,但无法在Mvc3源代码中找到它。
//model class
public class Foo
{
public string Bar { get; set; }
public BarTypeEnum BarType { get; set; }
}
//html helper class
public static class HtmlHelpers {
public static string FooLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) where TModel:Foo
{
BarTypeEnum barType = ExpressionHelper.GetExpressionText(expression);
string field = ((Foo)html.ViewData.Model).BarType;
return GlobalizeText(enumHelper.stringvalue(barType), field);
}
}
//html
@model Foo
<div>@Html.FooLabelFor(m => m.Bar)</div>
您希望作为附加参数传递给帮助程序的柱线类型和字段名称,如下所示:
public static string FooLabelFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, BarTypeEnum barType, string fieldName)
{
//...
}
然后,您需要在帮助程序的正文中添加一些代码来确定标签的适当文本,假设您将该文本放入名为 theText
的变量中。 现在您所需要的只是:
var theLabel = htmlHelper.Label(id, HttpUtility.HtmlEncode(theText));
return MvcHtmlString.Create(theLabel);
我希望这有所帮助。