编程语言
首页 > 编程语言> > c# – 从模型元数据中解析元数据displayname?

c# – 从模型元数据中解析元数据displayname?

作者:互联网

我已经使用附加参数进行了标签扩展,但是当我使用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属性中设置的名称?

解决方法:

我错过了这个事实,当我发布我之前的答案时,你的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不起作用.

标签:c,asp-net-mvc-3,html-helper
来源: https://codeday.me/bug/20190715/1470890.html