简体   繁体   English

ASP.Net MVC中的Linq和DisplayFor

[英]Linq and DisplayFor in ASP.Net MVC

I've got a model that has an ICollection of telephone numbers. 我有一个带有ICollection电话号码的模型。 In my view I want to display the value for the record that is marked as Primary. 在我看来,我想显示标记为Primary的记录的值。

@Html.DisplayFor(model => model.Telephones.Where(a=>a.Primary==true).Number)

The .Number is not allowed in the Linq syntax. Linq语法中不允许使用.Number How would one go about making the above line work or rather what is the proper way to display the number? 如何使上述线路工作或者更确切地说显示数字的正确方法是什么?

I probably should do the logic in the controller and put the value in a view model but it seems like this should be doable. 我可能应该在控制器中执行逻辑并将值放在视图模型中,但看起来这应该是可行的。

The Where extension method returns an IEnumerable<T> . Where扩展方法返回IEnumerable<T> If you just want the first item which satisfies the condition, use First : 如果您只想要满足条件的第一项,请使用First

@Html.DisplayFor(model => model.Telephones.First(a => a.Primary).Number)

If you also need to ensure that exactly one item in the set satisfies the condition (and throw an exception otherwise), consider using Single : 如果您还需要确保集合中的一个项目满足条件(否则抛出异常),请考虑使用Single

@Html.DisplayFor(model => model.Telephones.Single(a => a.Primary).Number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM