C# 抽象属性上的MVC属性
我有一个抽象模型C# 抽象属性上的MVC属性,c#,.net,asp.net-mvc,C#,.net,Asp.net Mvc,我有一个抽象模型 public abstract class Treasure { public abstract int Value { get; } public abstract string Label { get; } } 和一个实现 public class Coins : Treasure { [DisplayName("Coin Value")] public override int Value { get { ... }
public abstract class Treasure {
public abstract int Value { get; }
public abstract string Label { get; }
}
和一个实现
public class Coins : Treasure {
[DisplayName("Coin Value")]
public override int Value {
get { ... }
}
[DisplayName("Coins")]
public override string Label {
get { ... }
}
当我使用
Html.LabelFor
时,我的coins对象在我的视图中不显示“coins”作为其标签。如果我将DisplayName属性移动到宝藏中,它会工作。。。但是我需要能够为不同的Treasure类实现更改标签。这有可能吗?如果视图中的模型是硬币,我可以让它正常工作。然而,如果这个模型是宝藏,它就失败了。为什么?因为当Html助手呈现Html时,它只查看视图中指定的模型类型,而不是实际对象的对象类型。当它去获得属性时,它将只获得宝藏属性,而不是硬币属性。我认为您必须为此编写自己的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);
}
视图中的模型是什么。。。宝藏还是硬币?您是否尝试在宝藏对象和硬币对象上实现默认值?只是一个想法。只是为了清楚起见,最好能看到Razor标记中包含“LabelFor”的片段。代码解释得很好。实际上,它关注的是
@model
声明,而不是实际的类型。
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);
}