DisplayNameFor()从列表<对象>在型号 [英] DisplayNameFor() From List<Object> in Model

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

问题描述

我相信这pretty简单,我似乎没有找到显示的显示名称我的模型内的一个列表中的项目以正确的方式。

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全名。显然,

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);

是行不通的,以及

wouldn't work, and

@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解析前pression,而不是实际执行它。这使得它找到正确的属性和特性,而无需那里是列表中的一个元素。

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.

值得注意的是,参数(模式以上)甚至不需要使用。这工作,也:

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()从列表&LT;对象&gt;在型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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