Do you use View Models instead of ViewData?
Last updated by Brady Stroud [SSW] 7 months ago.See historyMVC provides a ViewData collection in which you can store miscellaneous pieces of information to pass to the View. It’s also accessible it as a Dynamic object by using the ViewBag. However, you should avoid using ViewData or ViewBag because it isn’t type-safe and relies on Magic Strings.
public ActionResult Index() {
ViewData["Message"] = "Some Message";
return View();
}
<h1><%: ViewData["Message"] &></h1>
Figure: Bad example – ViewData being used to pass information to the View isn’t type-safe
public ActionResult Index() {
var model = new IndexViewModel();
model.Message = "Some Message";
return View();
}
<h1><%: Model.Message %></h1>
Figure: Good example – Using a ViewModel is a safer way to pass data