如果视图中的模型是硬币,我可以让它正常工作。但是,如果模型是宝藏,它会失败。为什么?因为当 Html Helper 渲染 Html 时,它只查看视图中指定的模型类型,而不是实际对象的对象类型。当它去获取属性时,它只会获取Treasure而不是Coins的属性。我认为您必须为此编写自己的 Html 助手。
internal static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, IDictionary<string, object> htmlAttributes, ModelMetadataProvider metadataProvider)
{
return LabelExtensions.LabelHelper((HtmlHelper) html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData, metadataProvider), ExpressionHelper.GetExpressionText((LambdaExpression) expression), labelText, htmlAttributes);
}
在幕后,MVC 用于ModelMetadata.FromLambdaExpression<TModel, TValue>
查找“DisplayName”,当它在传入的类型上找不到一个时......它返回PropertyName
.
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, IDictionary<string, object> htmlAttributes = null)
{
string str = labelText;
if (str == null)
{
string displayName = metadata.DisplayName;
if (displayName == null)
{
string propertyName = metadata.PropertyName;
if (propertyName == null)
str = Enumerable.Last<string>((IEnumerable<string>) htmlFieldName.Split(new char[1]
{
'.'
}));
else
str = propertyName;
}
else
str = displayName;
}
string innerText = str;
if (string.IsNullOrEmpty(innerText))
return MvcHtmlString.Empty;
TagBuilder tagBuilder1 = new TagBuilder("label");
tagBuilder1.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tagBuilder1.SetInnerText(innerText);
TagBuilder tagBuilder2 = tagBuilder1;
bool flag = true;
IDictionary<string, object> attributes = htmlAttributes;
int num = flag ? 1 : 0;
tagBuilder2.MergeAttributes<string, object>(attributes, num != 0);
return TagBuilderExtensions.ToMvcHtmlString(tagBuilder1, TagRenderMode.Normal);
}