DisplayNameFor() 从列表<对象>在模型中 [英] DisplayNameFor() From List&lt;Object&gt; in Model

查看:41
本文介绍了DisplayNameFor() 从列表<对象>在模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这很简单,我似乎无法找到正确的方法来显示模型中列表中项目的显示名称.

I believe this is pretty simple, I just can't seem to find the right way to show the display name for an item within a list within my model.

我的简化模型:

public class PersonViewModel
{
    public long ID { get; set; }

    private List<PersonNameViewModel> names = new List<PersonNameViewModel>();

    [Display(Name = "Names")]
    public List<PersonNameViewModel> Names { get { return names; } set { names = value; } }      
}

和名称:

public class PersonNameViewModel
{
    public long ID { get; set; }

    [Display(Name = "Set Primary")]
    public bool IsPrimary { get; set; }

    [Display(Name = "Full Name")]
    public string FullName { get; set; }
}

现在我想制作一个表格来显示一个人的所有姓名,并获得 DisplayNameFor FullName.显然,

Now I'd like to make a table to show all the names for a person, and get the DisplayNameFor FullName. Obviously,

@Html.DisplayNameFor(model => model.Names.FullName);

行不通,并且

@Html.DisplayNameFor(model => model.Names[0].FullName);  

如果没有名字就会中断.是否有一种最佳方式"可以在此处获取显示名称?

will break if there are no names. Is there a 'best way' to obtain the display name here?

推荐答案

这确实有效,即使列表中没有项目:

This actually works, even without items in the list:

@Html.DisplayNameFor(model => model.Names[0].FullName)

之所以有效,是因为 MVC 会解析表达式而不是实际执行它.这使它可以找到正确的属性和属性,而无需列表中的元素.

It works because MVC parses the expression instead of actually executing it. This lets it find that right property and attribute without needing there to be an element in the list.

值得注意的是,甚至不需要使用参数(上面的model).这也有效:

It's worth noting that the parameter (model above) doesn't even need to be used. This works, too:

@Html.DisplayNameFor(dummy => Model.Names[0].FullName)

就像这样:

@{ Namespace.Of.PersonNameViewModel dummyModel = null; }
@Html.DisplayNameFor(dummyParam => dummyModel.FullName)

这篇关于DisplayNameFor() 从列表<对象>在模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆