Wednesday, September 24, 2014

Implement Viewmodel in MVC Asp.net

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 { getset; }
        public string ProductName { getset; }
        public int Quantity { getset; }
        public decimal UnitPrice { getset; }
        public decimal TotalPrice { getset; }


    }



    public class ShoppingCartViewModel
    {
        public ShoppingCartViewModel()
        {
            _shoppingCartItem = new List<ShoppingCart>();
        }
        public decimal AllTotal { getset; }
        public decimal AllTotalWithVat { getset; }
        public List<ShoppingCart> _shoppingCartItem { getset; }

    }
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

http://blogsiteslist.com