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.