SSW Foursquare

Do you use View Models instead of ViewData?

Last updated by Brook Jeynes [SSW] 9 months ago.See history

MVC 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

We open source. Powered by GitHub