MVC3扩展方法<tmodel,tvalue =“”> </tmodel,>

时间:2012-04-25 18:32:22

标签: c# asp.net-mvc-3

编辑: 感谢David Ruttka,在查看Mvc3 RTM版本的LabelExtensions.cs后,我能够弄明白。

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

对于模型,我需要指定我想要施放的模型和Helper- TModel:Foo 然后我可以得到模型: BarTypeEnum barType =((Foo)html.ViewData.Model).BarType;

我已将下面的来源更新为适用于我的内容。

/ EDIT

我正在尝试在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>

1 个答案:

答案 0 :(得分: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);

我希望有所帮助。

相关问题