Over a million developers have joined DZone.

ASP.NET MVC 3: New ViewModel is dynamic ViewData


ASP.NET MVC 3 introduces new ViewModel property of Controller that you can use to assign different properties to the model of your view. ViewModel is dynamic by type. In this posting I will show you how to use ViewModel property in your ASP.NET MVC applications.

Suppose you have controller for products that has method Details() to show details of product requested by visitor. We want to use dynamic ViewModel to get data to details view.

So, here is our controller that uses dynamic ViewModel.

public ActionResult Details(int productId)
var product = _repository.GetProductById(productId);

if (Request.IsAuthenticated)
ViewModel.VisitorName = HttpContext.User.Identity.Name;
ViewModel.VisitorName = "visitor";

ViewModel.ProductName = product.Name;
ViewModel.ProductUnitPrice = product.UnitPrice;
ViewModel.ProductDescription = product.Description;

// ...

return View();

And here is the fragment of view that shows product details.

<h2><%= ViewModel.ProductName  %> (<%= ViewModel.ProductPrice  %> EUR)</h2>
<%= ViewModel.ProductDescription %>
User can see besides other stuff the fragment like this.

Let’s try now what happens when we use good old ViewData instead of ViewModel.

public ActionResult Details(int productId)
var product = _repository.GetProductById(productId);

if (Request.IsAuthenticated)
ViewData["VisitorName"] = HttpContext.User.Identity.Name;
ViewData["VisitorName"] = "visitor";

ViewData["ProductName"] = product.Name;
ViewData["ProductUnitPrice"] = product.UnitPrice;
ViewData["ProductDescription"] = product.Description;

// ...

return View();

Don’t make any other changes to code. Compile your project and refresh product page. Guess what … the result is same as before! Why should ViewData and ViewModel be synchronized? Think about controller unit test and it should be clear.


ViewModel property of Controller is great addition to ASP.NET MVC and it makes our code and views more readable. Instead of using ViewData or strongly typed views we can use ViewModel to form our model objects dynamically and give them to views.


Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}