Declaring List inside a Model

asp.net, asp.net-mvc, asp.net-mvc-4, c#, razor

Solution

Why do you want to pass `@model Doc.Web.Models.Common.School` to the view ? where you need a "list" on your view.

Here is something you can try...

Class structure : Create a SchoolList class

public class School
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public class SchoolList 
{
    public List<School> Schools { get; set; }
}

Pass to view :

@model Doc.Web.Models.Common.SchoolList

Controller :

public ActionResult Index()
{
    SchoolList model= new SchoolList();
    SchoolRepository rep = new SchoolRepository();

    //Read list of schools from database
    model.Schools = rep.GetData(); 

    return View(model);
}

So this way you don't need to pass an IEnumerable to the view and get the job done.

Problem

I have a scenario where I don't want to pass a model as an `Ienumerable` list to the Razor View. ``` public class School { public int ID { get; set; } public string Name { get; set; } public string Address { get; set; } } ``` I need to pass the model to view as below. ``` @model Doc.Web.Models.Common.School ``` not as ``` @model IEnumerable<Doc.Web.Models.Common.School> ``` So, I decalred a List inside the same Model ``` public class School { public School() { lstSchool = new List<School>(); } public int ID { get; set; } public string Name { get; set; } public string Address { get; set; } public List<School> lstSchool { get; set; } } ``` Then in the controller ``` public ActionResult Index() { School model= new School(); SchoolRepository rep = new SchoolRepository(); model.lstSchool= rep.GetData();//Read list of schools from database return View(model); } ``` is this the proper way to achieve this?

Original source