Monday, 4 June 2018

What is ViewModel? Use more than one model in View using View Model.

In the previous blog, I wrote about How to Pass data to View?
In this blog, we will see What is ViewModel and How to use it?

What is ViewModel?


In ASP.Net MVC, a view cannot have more than one Model. So, in case you wish to fetch properties from more than one Model on your View then we have to use ViewModel.

Let's demonstrate this by an example.

Create a Domain class - Product

public class Products
    {
        public int ProductId { get; set; }
        [Required ]
        [StringLength(300)]
        public string ProductName { get; set; }
        [Required]
        [ProductCostCheck]
        public int ProductCost { get; set; }
        [Display (Name="Discount Value")]
        public int Discount { get; set; }
    }

Create another Domain class - Customer

public class Customer
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
    }

Create a ViewModel - ProductsViewModel (Try to add this class in a separate folder - ViewModels)

public class ProductsViewModel
    {
        public Products Products { get; set; }
        public List<Customer> Customers { get; set; }
    }


Add a Controller class with Action name - DisplayProductName

Now add below code to your Action.

public ActionResult DisplayProductName()
        {
            var product = new Products { ProductName = "Product1" };

            List<Customer> listCustomers = new List<Customer>();
            listCustomers.Add(new Customer { CustomerId = 1, CustomerName = "Customer1" });
            listCustomers.Add(new Customer { CustomerId = 2, CustomerName = "Customer2" });
            listCustomers.Add(new Customer { CustomerId = 3, CustomerName = "Customer3" });
            listCustomers.Add(new Customer { CustomerId = 4, CustomerName = "Customer4" });
           
            var viewmodel = new ProductsViewModel
            {
                Products = product,
                Customers = listCustomers
            };

            return View(viewmodel);
        }

Now implement ViewModel in View as shown below.

@model MVCPractice.ViewModels.ProductsViewModel
@{
    ViewBag.Title = "DisplayProductName";
}

 <h2>@Model.Products.ProductName</h2>
<hr />
<ul>
@foreach(var item in Model.Customers)
{
    <li>
        @item.CustomerId - @item.CustomerName
    </li>
}
</ul>

Interview Question - Can we pass more than on Model to our View? Or How can we pass more than one model to the View?

Answer - We can pass more than one Model to the View using ViewModel.


Hope you understand the use of ViewModel in ASP.Net MVC.

Next -

How to Pass data from Controller to View?



No comments:

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks