.net - Pass Objects from a controller to a view MVC -
this question has answer here:
- viewmodels or viewbag? 2 answers
i started in new job, must create app using mvc 5, have no experience in .net not sure if using best practice.
i have 2 models classrom , 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 passing icollection<> controller 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 data in view
<div> @foreach (var student in viewbag.students) { <div>@student.name</div> <div>@student.age</div> }
it works pretty need, anyway if add scaffolded controller, create this:
public actionresult index() { return view(db.students.tolist()); }
and 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, doing wrong? should use @model ienumerable instead of viewbag?
it better use @model ienumerable
because:
- it statically typed.
viewbag
dynamic lose type safety. - it leads cleaner design components (
viewmodels
,models
can reused).
ps: classrom
should classroom
believe.
good luck!
Comments
Post a Comment