【发布时间】:2016-02-23 02:04:35
【问题描述】:
我有几个自定义数据注释可用于编辑 ViewModel。
因为它们可以应用于任何类型的表单控件,所以我在每个EditorTemplate 中都对它们进行了测试。
任何人都可以推荐一种在 MVC 中重用这样的共享视图代码的方法吗?
我正在考虑使用 HtmlHelper 或 AppCode/Helper 类。不知道哪个最好,我对两者都有点新手。
@{
var htmlAttributesFromView = ViewData["htmlAttributes"] ?? new { };
var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesFromView, new { @class = "form-control" });
bool isDisplayInfoOnIconClickAttribute = false;
string title = "";
string description = "";
var infoOnClickAttributes = (ViewData.ModelMetadata).ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(DisplayInfoOnIconClickAttribute), false);
if (infoOnClickAttributes.Length > 0)
{
DisplayInfoOnIconClickAttribute attribute = infoOnClickAttributes[0] as DisplayInfoOnIconClickAttribute;
isDisplayInfoOnIconClickAttribute = true;
title = attribute.Title;
description = attribute.Description;
}
bool isDisplayTextInfoAttribute = false;
string info = "";
var textInfoAttributes = (ViewData.ModelMetadata).ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(DisplayTextInfoAttribute), false);
if (textInfoAttributes.Length > 0)
{
DisplayTextInfoAttribute attribute = textInfoAttributes[0] as DisplayTextInfoAttribute;
isDisplayTextInfoAttribute = true;
info = attribute.Info;
}
}
<div class="form-group">
@Html.LabelFor(model => model, htmlAttributes: new { @class = "control-label col-md-3 text-right-md" })
<div class="col-md-8">
@Html.TextBoxFor(model => model, htmlAttributes)
@Html.ValidationMessageFor(model => model)
</div>
<a class="infoonclick col-md-1" title="@Html.DisplayNameFor(model => model)" data-content="@Html.DescriptionFor(model => model)">
<span class="fa fa-info-circle"></span>
</a>
</div>
【问题讨论】:
-
要放入
EditorTemplate的代码非常多,而且有点不清楚isDisplayInfoOnIconClickAttribute、title、description等所有变量的用途 - 你不要似乎从来没有使用过它们。通常,如果您想基于属性生成一些 html,则该属性会实现IMetadataAware,它将值添加到ModelMetadata.AdditionalValues,然后您创建自己的HtmlHelper扩展方法来输出 html。 -
太棒了,谢谢。这听起来更像。我需要在
IMetadataAware.OnMetadataCreated()中输入任何内容还是可以将其留空?你有没有机会提供一个简短的例子来说明我如何将ModelMetadata.AdditionalValues变成HtmlHelper?这将定义为 anwser :) -
它有点不清楚你想要实现什么,但refer this answer 是一个使用实现
IMetadataAware的属性的示例。然后是根据链接创建HtmlHelper扩展方法,还是只是读取EditorTemplate中的ViewData.ModelMetadata.AdditionalProperties值实际上取决于其他因素。 -
完美,非常感谢。我添加了一个修改后的代码示例,希望现在更清楚了。代码现在已经被简化了,我认为
HtmlHelper会有点矫枉过正。 -
建议您将您的编辑移动到一个自我回答中并接受它,以便您可以关闭它。
标签: asp.net-mvc data-annotations mvc-editor-templates