Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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.

ASP.NET MVC 3: ViewModel property

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;
    else
        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>
<p>
    <%= ViewModel.ProductDescription  %>
</p>

User can see besides other stuff the fragment like this.

ASP.NET MVC 3: Example output of view

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;
    else
        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.

Conclusion

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.

Posted: Jul 27 2010, 09:26 PM by DigiMortal | with 19 comment(s)
Filed under: ,

Comments

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# July 27, 2010 2:27 PM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# July 27, 2010 2:28 PM

progg.ru said:

Thank you for submitting this cool story - Trackback from progg.ru

# July 27, 2010 2:29 PM

Vaibhav Sharma said:

Hey gunnarpeipman... Thanks to explain about this cool property...........

# July 27, 2010 2:52 PM

Twitter Trackbacks for ASP.NET MVC 3: New ViewModel is dynamic ViewData - Gunnar Peipman's ASP.NET blog [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 ASP.NET MVC 3: New ViewModel is dynamic ViewData - Gunnar Peipman's ASP.NET blog         [asp.net]        on Topsy.com

# July 27, 2010 3:00 PM

ASP.NET MVC 3: New ViewModel is dynamic ViewData – Gunnar … - asp said:

Pingback from  ASP.NET MVC 3: New ViewModel is dynamic ViewData &#8211; Gunnar &#8230; - asp

# July 27, 2010 7:04 PM

U60 Urban Gear Backpack said:

Pingback from  U60 Urban Gear Backpack

# July 28, 2010 3:18 AM

Hideaway | Movie City Online said:

Pingback from  Hideaway | Movie City Online

# July 28, 2010 3:57 AM

Sanctuary: The Complete Second Season | Movie City Online said:

Pingback from  Sanctuary: The Complete Second Season | Movie City Online

# July 28, 2010 4:07 AM

Adam said:

Nice, but these days you should be using <%: instead of <%=  

:)

# July 28, 2010 10:22 AM

Mattia Baldinger's Blog said:

.NET Links of the Week #30

# August 2, 2010 3:47 PM

ASP.NET MVC Archived Blog Posts, Page 1 said:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# August 3, 2010 11:45 PM

Keyur Patel said:

Really cool article for ViewData and ViewModel difference.

# August 11, 2010 9:35 AM

Deepak said:

I don't like the use of ViewData at all.

1) You don't define what is required.

2) No compile time errors

I create a class now i.e. ProductViewModel

public class ProductViewModel{

   public Product Product {get; set;}

   public decimal Price {get; set;}

}

And send this as my view to the model.

Got this from the NerdDinner sample chapter by ScottGu

# November 1, 2010 8:52 AM

Lan??ado o ASP.NET MVC 3 RC | ??talo Chesley said:

Pingback from  Lan??ado o ASP.NET MVC 3 RC | ??talo Chesley

# November 11, 2010 2:17 PM

Mark said:

Thanks! The light just went on!

# December 17, 2010 5:53 PM

Rahul Gangwar said:

The justification at end is wrong. You cannot always replace strong types with dynamic types and inherit all drawbacks of dynamic programming like performance overhead, intellisense missing etc. It should be used only when dynamic programming makes sense. Given that all code is within our control (and within managed world) we should mostly use correct patterns (like dynamic polymorphism with interfaces) and replace it with dynamic programming. Always remember that Dynamic programming should be the last resort not the first.

# January 5, 2011 3:10 PM

dk said:

@Rahul. "Dynamic programming should be the last resort not the first"???  Dynamic programming should and probably will be used far more than it is today by most msft devs.  It sounds to me like you have gotten the wrong impression of dynamic programming.  

# February 15, 2011 2:29 AM

gotibandhu said:

Hi,

Nice article, thanks for sharing with us. It's really helpful for me and this link...

www.mindstick.com/.../443c4cc1-a69c-46e4-bf18-2c27230f36bb

also helped me to complete my task.

# October 13, 2011 9:54 AM