MVC 3 model foreach filter

不羁岁月 提交于 2020-01-24 10:34:08

问题


I have the following razor syntax

  @{
     foreach (var p in Model)
     { 
       <b>@p.Age</b>
     }
    }

I would like to filter the foreach loop to only look at the Model records where p.City = "New York"

What would my syntax look like ?

I hope that I am explaing this right.

Thanks


回答1:


 @foreach (var p in Model.Where(i => i.City == "New York")) { 
    <b>@p.Age</b>  
 }

You might decide to do this filtering in the controller action, depending on whether you need other model records that don't have a city of "New York" in your view or not.




回答2:


You can use LINQ (http://msdn.microsoft.com/en-us/library/bb397896.aspx) extension methods like "Where" to apply the filter. You also don't need the outer "@{}", you can just put an "@" in front of the foreach and Razor will figure out what you mean. Something like:

@foreach (var p in Model.Where(item => item.City == "New York")) {
    <b>@p.Age</b>
}


来源:https://stackoverflow.com/questions/7124762/mvc-3-model-foreach-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!