speckis
speckis

Reputation: 67

Asp.net MVC - where query for multiple grids

Update 2

Thanks to both Thomas Boby and Sam C. Both had good answers and perfect solution to this problem!

Here's my problem: I want my view to show four grids/columns with different textboxes. Example, when I create a Post Message I add a Priority level, 1-5, to it.

Now, I simply want to foreach every column where the "Priority = X", so the 1's shows on one column, and Posts with priority 2 shows on another column. Do you get it? Or am I really bad at explaining this.

Model class:

 public enum Priority
{
    First = 1,
    Second = 2,
    Third = 3,
    Forth = 4,
    Fifth = 5,
}

public class Post
{
    public int postId { get; set; }

    public string postMsg { get; set; }

    public Priority priority { get; set; }
}

In my view I would want to do it like this:

    @foreach (var item in Model.Posts) // Where Model.priority = 1
    {
      <div class="col-md-2">
        <div class=" panel panel-default">
            @Html.DisplayFor(modelItem => item.postMsg, new { @class = "panel-body" })
        </div>
      </div>
    }

 @foreach (var item in Model.Posts) // Where Model.priority = 2
    {
      <div class="col-md-2">
        <div class=" panel panel-default">
            @Html.DisplayFor(modelItem => item.postMsg, new { @class = "panel-body" })
        </div>
      </div>
    }

The thing is I don't know how to make the "Where Model.priority = 1" query. I'm not sure if I can make a query like that in the foreach?

Update

To make things much more simpler: I want to have a different "Select Where" query for different divs.

Upvotes: 0

Views: 209

Answers (2)

Thomas Boby
Thomas Boby

Reputation: 789

Using System.Linq something like:

@foreach (var item in Model.Posts.Where(x => x.priority == Priority.First))
{
...
}

Would loop over every item with a priority of 1.

Upvotes: 0

Sam.C
Sam.C

Reputation: 1621

something like this ???

@foreach( var p in Enum.GetValues( typeof( Priority) ).Cast< Priority >().OrderBy(x=>(int)x) ) //sorted from first priority to fifth
{
    @foreach (var item in Model.Posts.Where(x=>x.Priority == p)) 
    {
        <div class="col-md-2">
            <div class=" panel panel-default">
                @Html.DisplayFor(modelItem => item.postMsg, new { @class = "panel-body" })
            </div>
        </div>
    }
}

Upvotes: 1

Related Questions