Search code examples
c#asp.net-mvc-5service-layer

Using ViewBag or calling service method on View


I wonder what should I use when to fill SelectList on View. I know two ways to do that. First; Set ViewBag on controller's get method.

    ViewBag.DepartmentList = new SelectList(_departmentService.GetAll(), "Id", "Name", selectedValue: user.DepartmentId);

and then use it on view like (you can also do it with ViewData)

    @Html.DropDownListFor(model => model.DepartmentId, (IEnumerable<SelectListItem>)ViewBag.DepartmentList )

Second way that I know is calling service method from view directly:

    @Html.DropDownListFor(model=>model.DepartmentId,new SelectList((new DepartmentService()).GetAll(),"Id","Name", selectedValue: Model.DepartmentId ))

So, sometimes we should return to view passing model to method on the controller post method especially there is an error or ModelState is not valid. As you know, when doing this ViewBag.DepartmentList should be filled on post method, again. On the other hand using second way, there is no need to create and fill ViewBag.DepartmentList either get and post method. But I wonder if there is any difference or which one should i use? Why?


Solution

  • neither of those two options is a good way to go. Consider using a ViewModel instead.