ViewData and ViewModel in MVC ASP.NET

十年热恋 提交于 2020-01-01 08:43:09

问题


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


回答1:


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.




回答2:


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 :

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.


来源:https://stackoverflow.com/questions/5177241/viewdata-and-viewmodel-in-mvc-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!