Do you use View Models instead of ViewData?
  v1.0 Posted at 8/03/2013 5:27 AM by Tiago Araujo

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

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address: