2012-04-25 65 views
2

编辑: 感谢David Ruttka,在从Mvc3的RTM版本中查看LabelExtensions.cs后,我能够发现它。MVC3扩展方法<TModel,TValue>

对于字段名称: string field = ExpressionHelper.GetExpressionText(expression);

对于模型,我需要指定我想投作为Helper- 其中的TModel模型:富 然后我能得到的模型: BarTypeEnum棒型=((美孚)html.ViewData.Model ).BarType;

我已经更新了以下源代码,以了解对我有用的内容。

/EDIT

我试图创建一个类似的HTML帮助功能MVC3到LabelFor返回基于Foo.BarType一个字符串值和Foo的领域从HTML中传递的名称。

在下面的函数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> 
+0

FWIW'LabelFor'可以在'LabelExtensions'类中找到,即'\ src \ SystemWebMvc \ Mvc \ Html \ LabelExtensions.cs' – 2012-04-25 18:37:06

+0

您还没有在这里提过一个问题。 – Robaticus 2012-04-25 18:39:49

+0

@DavidRuttka - codeplex上的源代码浏览器:https://aspnet.codeplex.com/SourceControl/changeset/view/77537,源代码下载不包含LabelExtensions.cs。你知道我可以下载它吗? – StormRider01 2012-04-25 18:48:48

回答

0

酒吧类型和字段的名字,你会希望在作为附加参数传递给帮手,像这样:

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); 

我希望有帮助。

+0

添加(BarTypeEnum barType,字符串fieldName)是不必要的,因为我应该能够从html参数中抽取barType,并从表达式中抽取fieldName。 – StormRider01 2012-04-25 20:20:53