4

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

[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")正常工作并在此示例中返回“名称标签”。

4

1 回答 1

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

以及“名称标签”的 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获取“名称标签”,代码如下所示:

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

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

String displayName = metadata.DisplayName; 

或者更好的方法:

String displayName = metadata.GetDisplayName;
于 2015-05-19T08:37:30.037 回答