Jesna
Jesna

Reputation: 55

Can I use IEnumerable<> inside a View?

In _Layout.cshtml

    @model DynaPortalMVC.Models.Page
@using System.Linq
<ul>
     @IEnumerable<model.Page> pages = model.Where(x=>x.CompanyID == 1);
     @foreach (var item in pages)
     {
       <li>item.Title</li>
     }
 </ul>

In view iam trying to filter the model object called 'page' and get a list of pages whose id is 1. I need to iterate through this to show the menu.

Code inside Controller

public ActionResult Menu(string PageName)
    {
        //
        return View(PageName, db.Pages);
    } 

Please tell me, how to filter out this model object to a list? I get errors on using IEnumerable.

Solved

I changed the model object to IEnumerable in view page.

@model IEnumerable<DynaPortalMVC.Models.Page>

Upvotes: 1

Views: 2759

Answers (3)

kavitha Reddy
kavitha Reddy

Reputation: 3333

@model IEnumerable<DynaPortalMVC.Models.Page>
@{
    ViewBag.Title = "Page";

}

Upvotes: 0

von v.
von v.

Reputation: 17108

You can skip assigning the result of your query into an IEnumerable variable unless you will use it somewhere else on the page. So you can just do this:

@model DynaPortalMVC.Models.Page
@using System.Linq
<ul>
     @foreach (var item in model.Where(x=>x.CompanyID == 1))
     {
       <li>@item.Title</li>
     }
 </ul>

Upvotes: 2

vborutenko
vborutenko

Reputation: 4443

You need

@ {IEnumerable<model.Page> pages = Model.Where(x=>x.CompanyID == 1);}

Upvotes: 1

Related Questions