Search code examples
.netasp.net-mvcentity-frameworkviewbag

Pass Objects from a controller to a view MVC


I started in a new job, we must create an app using MVC 5, i have no experience in .NET so I not sure if I am using the best practice.

I have 2 models ClassRom and Students,

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

 public class ClassRom
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I am passing a ICollection<> from a controller to a views using ViewBag

IList<ClassRom> classes = db.Classes.ToList();
IList<Student> students = db.Students.ToList();
ViewBag.classes = classes;
ViewBag.students = students;
return View();

And using the data in a view

<div>
@foreach (var student in ViewBag.students)
{
    <div>@student.Name</div>
    <div>@student.Age</div>
}  

It works pretty well for what I need, anyway if I add a Scaffolded Controller, it will create something like this:

public ActionResult Index()
    {
        return View(db.Students.ToList());
    }

And the view

@model IEnumerable<School.Models.Student>
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Age)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
</tr>

}

My question is, Am i doing it wrong? should I use @model IEnumerable instead of ViewBag?


Solution

  • It is better to use @model IEnumerable because:

    • It is statically typed. A ViewBag is dynamic so you lose type safety.
    • It leads to a cleaner design where components (ViewModels and Models can be reused).

    PS: ClassRom should be ClassRoom I believe.

    Good luck!