SSW Foursquare

Do you use viewModel instead of ViewData?

Last updated by Brady Stroud [SSW] 10 months ago.See history

ASP.NET CORE MVC provides several ways to pass data to views:

  • Weakly typed data: ViewData and ViewBag
  • Strongly typed data: ViewModel

Both ViewData and ViewBag are dynamically resolved at runtime, which can often lead to runtime errors because they aren't type-safe and rely on Magic Strings.

Pass data using ViewData from Action:

public IActionResult About()
{
    ViewData["Message"] = "Hello World!";

    ViewData["User"] = new User()
    {
        Name = "Bob Northwind",
        Age = "35"
    };

    return View();
}

Figure: Bad example – ViewData is being used in Action which isn’t type-safe

Show data using ViewData in View:

@{
  var user = ViewData["User"] as User;
}

<h2>ViewData["Message"]</h2>

<div>
    @user.Name<br>
    @user.Age<br>
</div>

Figure: Bad example – Displaying not-safe data in View

So it is better to use ViewModel to pass data to views. Because it allows to take advantage of strong type checking, and the validity of types used in a view is checked at compile time.

Pass data using ViewModel from Action:

public IActionResult About()
{
    var viewModel = new UserViewModel()
    {
        Name = "Bob Northwind",
        Age = "35"
    };

    return View(viewModel);
}

Figure: Good example – ViewModel is being used in Action to pass data which is strongly-typed

Show data using ViewModel in View:

@model YourNamespace.ViewModels.UserViewModel

<div>
    @Model.Name<br>
    @Model.Age<br>
</div>

Figure: Good example – Displaying safe data in View


Damian Brady
Baba Kamyljanov
We open source.Loving SSW Rules? Star us on GitHub. Star
Stand by... we're migrating this site to TinaCMS