我已经使用附加参数进行了标签扩展,但是当我使用ViewData.ModelMetadata.DisplayName时,我没有从模型上的Diaplsy属性中获取显示名称?
我的模型有这样的用户名
[Display(Name = "User name")]
public string UserName { get; set; }
并像这样使用
@Html.LabelFor(m => m.SetupModel.UserName, @<span>No fancy characters mmkay?</span>)
使用这个html助手
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex, Func<object, HelperResult> template, string labelText = null) {
var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
var metadata = htmlHelper.ViewData.ModelMetadata;
string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText)) {
return MvcHtmlString.Empty;
}
var tag = new TagBuilder("label");
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tag.InnerHtml = string.Format(
"{0} {1}",
resolvedLabelText,
template(null).ToHtmlString()
);
return MvcHtmlString.Create(tag.ToString());
}
但结果是UserNameNo花哨的字符mmkay?当我认为它应该显示在display属性中设置的名称?
答案 0 :(得分:8)
当我发布我之前的回答时,我错过了在viewmodel中有不同对象的事实。以下只是为了说明这个想法,应该有更好的方法来做到这一点。
这就是诀窍:
var metadata = ModelMetadata.FromLambdaExpression(ex, htmlHelper.ViewData);
var resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
<击> 撞击>
<击>string resolvedLabelText = "";
if (htmlFieldName.Contains('.'))
{
var model = htmlFieldName.Split('.');
var metadata = htmlHelper.ViewData.ModelMetadata.Properties.FirstOrDefault(p => p.PropertyName == model[0] );
if (metadata != null)
{
metadata = metadata.Properties.FirstOrDefault(p => p.PropertyName == model[1]);
resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
}
else
resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
}
else
{
var metadata = htmlHelper.ViewData.ModelMetadata.Properties.First(p => p.PropertyName == htmlFieldName);
resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
}
上述内容对SomeObject.SomeObject.Propery
不起作用。
击>
答案 1 :(得分:4)
以防万一在MVC4中非常简单
@ViewData.ModelMetadata.PropertyName
@ViewData.ModelMetadata.DisplayName