How to Use ViewModel in Asp.Net MVC with Example

Here we will learn what is viewmodel in asp.net mvc and how to use viewmodel in asp.net mvc applications with example.

ViewModel in Asp.Net MVC

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.

 

viewmodel structure in asp.net mvc application

 

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.

Database Part

In this database part, we will create the required tables in the database with the following scripts.

Customer Table

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.

 

Customer Table in Database in sql server

Order table

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,)

Creating Asp.Net MVC Application  

Let's start with creating a new asp.net mvc 4 application for that Open visual studio à Go to File à Select New à Select Project.

 

create new asp.net mvc project from visual studio 2012

 

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.

 

give name of project as viewmodel in asp.net mvc application

 

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.

 

select basic template to create new application in asp.net mvc

 

After creating the application, here is the complete folder view.

 

viewmodel structure in asp.net mvc application

Installing Entity Framework in Application

For adding Entity framework, right-click on your application and from the list select "Manage NuGet Packages".

 

install entity framework in asp.net mvc application

 

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.

 

Installing Entity Framework in Asp.net mvc application

 

After adding, it will show an ok sign in green color.

 

After install entity framework in asp.net mvc application

 

After adding the Entity framework now, we are going to add ADO.NET Entity Data Model.

Adding 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.

 

Add ado.net entity data model in asp.net mvc application

 

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.

 

customerorderdb entity name in asp.net mvc application

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.

 

Choose Model Content for Ado.net model in database first approach

 

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.

Choosing Data Connection

Choose new database connection in viewmodel example

 

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.

 

Create new database connection in model first approach in asp.net mvc

 

After adding the database connection, our Entity Data Model Wizard will look like the below snapshot.

 

selecting entity data model new database connection in asp.net mvc

 

 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.

 

select order table from database in asp.net mvc

 

And the last click on the Finish button. Here is a snapshot after adding ADO.NET Entity Data Model.

 

Project structure after adding ado.net entity model in asp.net mvc applicaiton

 

Adding ViewModels Folder

Now let’s add ViewModels Folder to the project for keeping all ViewModel in the same folder.

 

add viewmodel folder in asp.net mvc application

Adding CustomerVM in ViewModels 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.

 

add new class in viewmodel folder in asp.net mvc

Once we select a class, the Add New Item dialog will popup in that select class and name as CustomerVM.cs.

 

give name to class file in asp.net mvc application

 

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.

Customer Entity

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; }

}

}

Order Entity

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; }

}

}

ViewModel (CustomerVM.cs)

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.

Adding Controller in Application

To add controller, right-click on Controller Folder inside that select Add and then select Controller.

 

add new controller in asp.net mvc application

 

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.

 

give name to controller in viewmodel asp.net mvc application

 

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();

}

 

}

}

Controller Action Methods (Index)

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.

Adding View in Application

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. 

 

Give name to view in viewmodel in asp.net mvc application

 

After Adding View (Index view), the complete folder view of the Project.

 

after add view our viewmodel asp.net mvc project structure

Index.cshtml View 

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.

 

tables data in asp.net mvc applicaiton

 

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.

 

output of viewmodel data in asp.net mvc application

 

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.