Here we will learn what is viewmodel in asp.net mvc and how to use viewmodel in asp.net mvc applications with example.
The viewmodel in asp.net mvc represents only the data we want to display, whether it is used for displaying or for taking input from view. If we want to display more than one model on view in asp.net mvc, we need to create a new viewmodel. The following image shows a visual representation of the view model in asp.net mvc.
Here we will learn asp.net mvc viewmodel with simple example if we have a Customer entity and Order entity. In view to display both entities (Customer entity + Order entity) data, then we need to create viewmodel (CustomerVM), and we will select the properties whichever we want to display from both entities (Customer entity + Order entity) and create a viewmodel.
Now start with creating a viewmodel in asp.net mvc. Before that, let's look at the table we are going to use in our application.
In this database part, we will create the required tables in the database with the following scripts.
Following is the script to create customer table in your database.
CREATE TABLE [dbo].[Customer](
[CustomerID] [int] IDENTITY(1,1) NOT NULL Primary key,
[Name] [varchar](100) NULL,
[Address] [varchar](300) NULL,
[Mobileno] [varchar](15) NULL,
[Birthdate] [datetime] NULL,
[EmailID] [varchar](300) NULL,)
Once we run the above script, it will create a Customer table as shown below.
Following is the script to create an order table in your database.
CREATE TABLE [dbo].[Order](
[OrderID] [int] IDENTITY(1,1) NOT NULL primary key,
[CustomerID] [int] NULL,
[OrderDate] [datetime] NULL,
[OrderPrice] [decimal](18, 0) NULL,)
Let's start with creating a new asp.net mvc 4 application for that Open visual studio à Go to File à Select New à Select Project.
After that, you will see a new dialog for selecting your Template and Project type. From Templates, select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application. Here we are giving the name as “TutorialViewModel” then finally click on the ok button.
After naming it, click on the OK new dialog to select a template in that Select Basic template and click ok like as shown below.
After creating the application, here is the complete folder view.
For adding Entity framework, right-click on your application and from the list select "Manage NuGet Packages".
The new dialog popup of “Manage NuGet Packages” inside the search box enter “EntityFramework”. After getting the search value, select EntityFramework click on the install button.
After adding, it will show an ok sign in green color.
After adding the Entity framework now, we are going to add ADO.NET Entity Data Model.
For adding ADO.NET Entity Data Model right-click on Model folder and select Add inside that Select ADO.NET Entity Data Model like as shown below.
After clicking on ADO.NET Entity Data Model, a New Dialog will popup for entering Item name inside that enter any name, but it must be unique and click on the OK button.
After that, a new Wizard will popup where we are going to configure the Entity Data Model. In this, we are going to use Database first.
From that select Generate from database and click on the Next button. After clicking on the Next button, a New Wizard will pop up for Choosing Data Connection.
Now click on New Connection, new Dialog will popup. Here we need to configure it. In Server name, you need to add your SQL Server Name and select either Using Windows Authentication or Using SQL Server Authentication to connect SQL Server. Here we selected Using SQL Server Authentication and entered the User name and Password of the SQL server. Last, we will select Database Name "OrderDB" once we did, click on the OK button as shown below.
After adding the database connection, our Entity Data Model Wizard will look like the below snapshot.
Now click on the Next button. A new wizard will popup for selecting database objects and in this, we will see all the tables we have created in the database.
And the last click on the Finish button. Here is a snapshot after adding ADO.NET Entity Data Model.
Now let’s add ViewModels Folder to the project for keeping all ViewModel in the same folder.
Inside this folder, let’s add ViewModel with name CustomerVM.cs for that right Click on ViewModels folder then select Add and last select Class like as shown below.
Once we select a class, the Add New Item dialog will popup in that select class and name as CustomerVM.cs.
After adding CustomerVM View Model that would contain code like as shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TutorialViewModel.ViewModels
{
public class CustomerVM
{
}
}
Now let’s check out Domain Models Entities, which we have added.
namespace TutorialViewModel.Models
{
using System;
using System.Collections.Generic;
public partial class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Mobileno { get; set; }
public Nullable<System.DateTime> Birthdate { get; set; }
public string EmailID { get; set; }
}
}
namespace TutorialViewModel.Models
{
using System;
using System.Collections.Generic;
public partial class Order
{
public int OrderID { get; set; }
public Nullable<int> CustomerID { get; set; }
public Nullable<System.DateTime> OrderDate { get; set; }
public Nullable<decimal> OrderPrice { get; set; }
}
}
After checking Entities now let’s add property from both Models to CustomerVM class. We took Name, Address, Mobileno from Customer model and Orderdate, and OrderPrice from Order Model to display on View.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TutorialViewModel.ViewModels
{
public class CustomerVM
{
public string Name { get; set; } // Customer
public string Address { get; set; } // Customer
public string Mobileno { get; set; } // Customer
public Nullable<System.DateTime> OrderDate { get; set; } // Order
public Nullable<decimal> OrderPrice { get; set; } // Order
}
}
After creating ViewModel (CustomerVM), now let's add a controller with Name CustomerOrderDetails.
To add controller, right-click on Controller Folder inside that select Add and then select Controller.
After selecting the controller, a new Add Controller Dialog will popup in that add Name CustomerOrderDetailsController. In the template, select Empty MVC Controller and click on the Add button.
After adding controller "CustomerOrderDetailsController" that will contain code like as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TutorialViewModel.Controllers
{
public class CustomerOrderDetailsController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
return View();
}
}
}
Inside this Controller, let’s write code for getting values from the database and populating ViewModel (CustomerVM).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TutorialViewModel.Models;
using TutorialViewModel.ViewModels;
namespace TutorialViewModel.Controllers
{
public class CustomerOrderDetailsController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
OrderDBEntities orderdb = new OrderDBEntities(); //dbcontect class
List<CustomerVM> CustomerVMlist = new List<CustomerVM>(); // to hold list of Customer and order details
var customerlist = (from Cust in orderdb.Customers
join Ord in orderdb.Orders on Cust.CustomerID equals Ord.CustomerID
selectnew { Cust.Name, Cust.Mobileno, Cust.Address, Ord.OrderDate, Ord.OrderPrice}).ToList();
//query getting data from database from joining two tables and storing data in customerlist
foreach (var item in customerlist)
{
CustomerVM objcvm = new CustomerVM(); // ViewModel
objcvm.Name = item.Name;
objcvm.Mobileno = item.Mobileno;
objcvm.Address = item.Address;
objcvm.OrderDate = item.OrderDate;
objcvm.OrderPrice = item.OrderPrice;
CustomerVMlist.Add(objcvm);
}
//Using foreach loop fill data from custmerlist to List<CustomerVM>.
return View(CustomerVMlist); //List of CustomerVM (ViewModel)
}
}
}
Now inside this controller, I have written a Linq query for getting data from the database with join both tables with (CustomerID) and stored it in (customerlist) and then applying a foreach loop for pushing that data into (List<CustomerVM> CustomerVMlist ) and lastly sending it to View.
For Adding View, right-click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in the below snapshot, we selected View engine as Razor, and we are going to create a strongly typed view for that we selected Model class CustomerVM. We want to create a List form for that we selected List in Scaffold template finally click on Add button.
After Adding View (Index view), the complete folder view of the Project.
After adding view below is a complete code of Index.cshtml which is generated.
@model IEnumerable<TutorialViewModel.ViewModels.CustomerVM>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<table cellspacing="5px;">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Mobileno)
</th>
<th>
@Html.DisplayNameFor(model => model.OrderDate)
</th>
<th>
@Html.DisplayNameFor(model => model.OrderPrice)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Mobileno)
</td>
<td>
@Html.DisplayFor(modelItem => item.OrderDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.OrderPrice)
</td>
</tr>
}
</table>
</body>
</html>
In the above generated View, we have data from both models Customer and Order and then we have stored data in CustomerVM (ViewModel) and finally displayed on the view. Our both tables Customer and Order contains data like as shown below.
Now, run the application and access the page by entering a URL like http://localhost:#####/CustomerOrderDetails/index.
Our output of viewmodel in asp.net mvc application will be like as shown below.
Generally, View Models in asp.net mvc are easy to use if we clear with information like where we want to display data or get input data from various domain models, then always use ViewModels.
This is how we can create viewmodel in asp.net mvc and use it in mvc applications based on our requirements.