您必须创建一个使用新模型或新 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;