C# MVC3扩展方法
编辑: 多亏了David Ruttka,我在查看了Mvc3 RTM发行版中的LabelExtensions.cs之后才明白了这一点 对于字段名: 字符串字段=ExpressionHelper.GetExpressionTextexpression 对于模型,我需要指定要为助手强制转换的模型- TModel:Foo在哪里 然后我就可以看到模型了: BarTypeEnum barType=Foohtml.ViewData.Model.barType 我已经将下面的源代码更新为适合我的 /编辑 我正在尝试创建一个类似于Mvc3中LabelFor的html帮助函数,以返回基于Foo.BarType和从html传入的Foo字段名称的字符串值 在下面的函数中,如何将模型和字段名传递到函数中 我去寻找System.Web.Mvc.htmlabelfor的源代码,但在Mvc3源代码中找不到它C# MVC3扩展方法,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,编辑: 多亏了David Ruttka,我在查看了Mvc3 RTM发行版中的LabelExtensions.cs之后才明白了这一点 对于字段名: 字符串字段=ExpressionHelper.GetExpressionTextexpression 对于模型,我需要指定要为助手强制转换的模型- TModel:Foo在哪里 然后我就可以看到模型了: BarTypeEnum barType=Foohtml.ViewData.Model.barType 我已经将下面的源代码更新为适合我的 /编辑 我正在
//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)
{
//...
}
我希望这会有所帮助。您希望作为附加参数传递给帮助程序的条类型和字段名,如下所示:
public static string FooLabelFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, BarTypeEnum barType, string fieldName)
{
//...
}
我希望这会有所帮助。FWIW LabelFor可以在LabelExtensions类中找到,即\src\SystemWebMvc\Mvc\Html\LabelExtensions.cs您实际上没有在这里提问。@DavidRuttka-codeplex:的源代码浏览器和下载的源代码都不包括LabelExtensions.cs。你知道我可以在哪里下载吗?由于其他原因,我今天早上9:41碰巧下载并解压了它。我在上面的路径中找到了该文件。我从FWIW LabelFor下载了ASP.NET MVC 3 RTM源代码,可以在LabelExtensions类中找到,即\src\SystemWebMvc\MVC\Html\LabelExtensions.cs。您实际上还没有在这里提问。@DavidRuttka-codeplex:的源代码浏览器和下载的源代码都不包括LabelExtensions.cs。你知道我可以在哪里下载吗?由于其他原因,我今天早上9:41碰巧下载并解压了它。我在上面的路径中找到了该文件。我从添加BarTypeEnum barType下载了ASP.NET MVC 3 RTM源代码,不需要字符串fieldName,因为我应该能够从html参数中提取barType,从表达式中提取fieldName。添加BarTypeEnum barType,不需要字符串fieldName,因为我应该能够从html参数中提取barType,和表达式中的字段名。