开发者

MVC 3 model foreach filter

开发者 https://www.devze.com 2023-03-29 14:21 出处:网络
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\"

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


 @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.


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>
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号