ViewData and ViewModel in MVC ASP.NET
Asked Answered
D

2

10

I'm new to .Net development, and now are following NerdDinner tutorial. Just wondering if any of you would be able to tell me

What is the differences between ViewData and ViewModel

(all I know is they are used to pass some form of data from controller to view) and perhaps tell me on what situation should I use ViewData instead of ViewModel and vice versa

Thanks in advance!

Sally

Diandiana answered 3/3, 2011 at 6:1 Comment(0)
C
8

ViewData:

In short, use ViewData as support data, such as a datasource to a SelectList.

ViewModel:

ASP.NET MVC ViewModel Pattern

When a Controller class decides to render an HTML response back to a client, it is responsible for explicitly passing to the view template all of the data needed to render the response. View templates should never perform any data retrieval or application logic – and should instead limit themselves to only have rendering code that is driven off of the model/data passed to it by the controller.

[...]

When using [the "ViewModel"] pattern we create strongly-typed classes that are optimized for our specific view scenarios, and which expose properties for the dynamic values/content needed by our view templates. Our controller classes can then populate and pass these view-optimized classes to our view template to use. This enables type-safety, compile-time checking, and editor intellisense within view templates.

Conch answered 3/3, 2011 at 6:13 Comment(1)
Thanks for your answer, incase anyone need to know more about this topic I also found a great blog entry relating to my question theminimalistdeveloper.com/2010/08/21/…Diandiana
P
12

What is ViewData ?

  • dictionary object that you put data into, which then becomes available to the view.

ViewData Sample

Controller Action method likes :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var featuredProduct = new Product
        {
            Name = "Smart Phone",
            QtyOnHand = 12
        };

        ViewData["FeaturedProduct"] = featuredProduct;
        return View();
    }
}

How to use ViewData on View ?

@{    
    var viewDataProduct = ViewData["FeaturedProduct"] as Product;
 }
<div>
    Today's Featured Product is!
    <h3>@viewDataProduct.Name</h3>
</div>

What is a ViewModel ?

  • Allow you to shape multiple entities from one or more data models or sources into a single object
  • Optimized for consumption and rendering by the view

Its like :

View Model image

How to use ViewModel with MVC 3 ?

Domain Model

public class Product
    {
        public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
        public Guid Id { get; set; }
        public string ProductName { get; set; }
    }

ViewModel

public class ProductViewModel
    {
        public Guid VmId { get; set; }

        [Required(ErrorMessage = "required")]
        public string ProductName { get; set; }

    }

Controller Action Method

[HttpGet]
public ActionResult AddProduct()
{
    //for initialize viewmodel
    var productViewModel = new ProductViewModel();

    //assign values for viewmodel
    productViewModel.ProductName = "Smart Phone";

    //send viewmodel into UI (View)
    return View("AddProduct", productViewModel);
}

View - AddProduct.cshtml

@model YourProject.ViewModels.ProductViewModel //set your viewmodel here

Conclusion

  • By using ViewModel can pass strongly-typed data into View
  • But ViewData is Loosely Typed.So Need to cast data on View
  • ViewModel can use for Complex scenarios such as merging more than one domain model
  • But ViewData can be used only for simple scenarios like bring data for the drop down list
  • ViewModel can use for attribute-based validation scenarios which needed for Ui
  • But Cannot use ViewData for such kind of validations
  • As a best practices always try to use strongly typed data with Views.ViewModel is the best candidate for that.
Pee answered 3/11, 2012 at 10:25 Comment(1)
I often find it cleaner to load your needed domain models into the ViewModel as private members and expose what you actually want for the view through properties. Also, if you set it up like an adapter, the data returned from the view through the viewmodel could then, in turn, hydrate data on the hidden domain objects.Disunity
C
8

ViewData:

In short, use ViewData as support data, such as a datasource to a SelectList.

ViewModel:

ASP.NET MVC ViewModel Pattern

When a Controller class decides to render an HTML response back to a client, it is responsible for explicitly passing to the view template all of the data needed to render the response. View templates should never perform any data retrieval or application logic – and should instead limit themselves to only have rendering code that is driven off of the model/data passed to it by the controller.

[...]

When using [the "ViewModel"] pattern we create strongly-typed classes that are optimized for our specific view scenarios, and which expose properties for the dynamic values/content needed by our view templates. Our controller classes can then populate and pass these view-optimized classes to our view template to use. This enables type-safety, compile-time checking, and editor intellisense within view templates.

Conch answered 3/3, 2011 at 6:13 Comment(1)
Thanks for your answer, incase anyone need to know more about this topic I also found a great blog entry relating to my question theminimalistdeveloper.com/2010/08/21/…Diandiana

© 2022 - 2024 — McMap. All rights reserved.