When we have to display the data from multiple classes in single page. A view model represents only the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdowns). I have shown you example .It is usesd t o pass the data strongly type . Here is example is given below
public class ShoppingCart
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal TotalPrice { get; set; }
}
public class ShoppingCartViewModel
{
public ShoppingCartViewModel()
{
_shoppingCartItem = new List<ShoppingCart>();
}
public decimal AllTotal { get; set; }
public decimal AllTotalWithVat { get; set; }
public List<ShoppingCart> _shoppingCartItem { get; set; }
}
Above two classes ShoppingCart and ShoppingCartViewModel . ShoppingCartViewModel class contains own properties and shopping cart items .So we called this class viewmodel
public ActionResult Index()
{
ShoppingCartViewModel obj = new ShoppingCartViewModel();//you have fillup class
return View(obj) ;
}
So we have return strongly type model from controller .now we have to display the view
In this way we have used the viewmodel in mvc asp.net
No comments:
Post a Comment