ModelMetadata.FromStringExpression不适用于嵌套属性

时间:2013-08-09 10:12:43

标签: asp.net-mvc-4 metadata

我的模型中有一个带有一些元数据的复杂类型;

[ComplexType]    
public class ComplexModel
{
    [Display("Name Label")]
    public string Name { get; set; }
}

public class MainModel
{
    // ...

    public ComplextModel ComplexModel { get; set; }
}

此代码正常运行;

Html.DisplayFor(model => model.ComplexModel.Name)

但这个没有;

Html.Display("ComplexModel.Name")

即使我走得更远,也发现问题是ModelMetadata.FromStringExpression

ModelMetadata.FromStringExpression("ComplexModel.Name", viewData)返回错误的结果。虽然ModelMetadata.FromLambdaExpression(expression, viewData)正常工作。

这是一个错误吗?

我只是希望Html.Display("ComplexModel.Name")正常工作,并在此示例中返回“名称标签”。

1 个答案:

答案 0 :(得分:0)

您必须创建一个使用新模型或新ViewData的新自定义HtmlHelper类,因此:

public static class CustomHtmlHelperExtensions
{
    public static HtmlHelper CustomHtmlHelper(this HtmlHelper helper, Object model)
    {
        ViewDataDictionary customViewData = new ViewDataDictionary(helper.ViewData) { Model = model };
        ViewDataContainer customViewDataContainer = new ViewDataContainer(customViewData);
        ViewContext customViewContext =
            new ViewContext(helper.ViewContext.Controller.ControllerContext, helper.ViewContext.View, customViewData, helper.ViewContext.TempData, helper.ViewContext.Writer);

        return new HtmlHelper(customViewContext, customViewDataContainer, helper.RouteCollection);

    }


    private class ViewDataContainer : IViewDataContainer
    {
        public ViewDataDictionary ViewData { get; set; }

        public ViewDataContainer(ViewDataDictionary viewData)
        {
            ViewData = viewData;
        }
    }

}

然后,您可以为Display编写自己的自定义助手,或者像这样使用Display助手:

@Html.CustomHtmlHelper(Model.ComplexModel).Display("Name");

"名称Lable"和

的DisplayName
@Html.CustomHtmlHelper(Model.ComplexModel).DisplayName("Name);

直接与@Html一起使用的自定义显示方法:

public static class CustomDisplayHelper
{
    public static MvcHtmlString CustomDisplay(this HtmlHelper helper, string expression, Object model)
    {
        HtmlHelper customHelper = helper.CustomHtmlHelper(model);
        return customHelper.Display(expression);
    }

    public static MvcHtmlString CustomDisplayName(this HtmlHelper helper, string expression, Object model)
    {
        HtmlHelper customHelper = helper.CustomHtmlHelper(model);
        return customHelper.DisplayName(expression);
    }
}

@Html.CustomDisplay("Name", Model.ComplexModel)
@Html.CustomDisplayName("Name", Model.ComplexModel)

如果您想使用ModelMetadata.FromStringExpression来获取"名称Lable" ,代码看起来像这样:

ViewDataDictionary myViewData = new ViewDataDictionary(Model.ComplexModel); 
ModelMetadata metadata ModelMetadata.FromStringExpression("Name", MyViewData); 

获取显示名称或任何其他属性:

String displayName = metadata.DisplayName; 

或更好的方式:

String displayName = metadata.GetDisplayName;