How to use View Model in MVC | Rajesh Gami

Summary

The view model in asp.net mvc represents only the data to display, regardless of whether it is used for display or to get input from the view. If you want to display multiple models in asp.net mvc, you need to create a new view model. The following image shows a visual representation of the view model in asp.net mvc.

Here we will learn asp.net mvc viewmodel using a simple example with a Customer entity and an Order entity. To display the data of both entities (Customer Entity + Order Entity), you need to create a view model (CustomerVM), select the properties to display from both Entity (Customer Entity + Order Entity) and model It is displayed.

viewmodel structure in asp.net mvc application
Then start creating the view model in asp.netmvc before looking at the tables used by your application.

Database part

In this database part, use the following script to create the required tables in the database.

Customer table

Below is a script to create a customer table in the 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,)
Running the above script will create a customer table as shown below.

Customer Table in Database in sql server

Order table

Below is a script to create an order table in the 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 an Asp.Net MVC Application  

Creating an Asp.Net MVC application VisualStudio Select Go To File> New > Select >Project

create new asp.net mvc project from visual studio 2012

After that, a new dialog box will appear where you can select the template and project type. Under Templates, under Web, select Visual C ++, and under Project Type, select ASP.NET MVC 4 Web Application. Name it "TutorialViewModel" here, and click the [OK] button at the end.

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

After giving a name, click [OK] to display a new dialog. To select a template in this, select the base template and click OK as shown below.

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

After building the application, this is the complete folder view.

viewmodel structure in asp.net mvc application

Installing Entity Framework on your application

To add Entity Framework, right-click on the application and select Manage NuGet Packages from the list.

install entity framework in asp.net mvc application

Once selected, a new dialog box called Manage NuGet Packages will appear in the search box, where you can type Entity Framework. After getting the search value, select Entity Framework and click the Install button.

Installing Entity Framework in Asp.net mvc application

    After adding a green OK symbol will be displayed.
After install entity framework in asp.net mvc application

After adding Entity Framework, add the ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

To add an ADO.NET entity data model, right-click on the model folder and select Add Inside. Select the ADO.NET entity data model as shown below.

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

Enter any name, but it must be unique and click the OK button.

customerorderdb entity name in asp.net mvc application
Then you will see a new wizard that configures the entity data model. In this case, use database first.

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

Then select Generate from database and click Next. Click the Next button to display the new data connection selection wizard. Select a data connection

 Data base connection

Choose new database connection in viewmodel example

Then click New Connection to bring up a new dialog. You need to configure it here. Under Server Name, you need to add the SQL Server name and select Use Windows Authentication or Use SQL Server Authentication to connect to SQL Server. Here, I selected Use SQL Server Authentication and entered the SQL server user name and password. Finally, select the database name "OrderDB". When you're done, click the OK button as shown below.

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

After adding the database connection, the Entity Data Model Wizard looks like this:

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

A new wizard for selecting database objects is displayed, showing all the tables you have created in the database.
select order table from database in asp.net mvc
Finally, click the Finish button. This is a snapshot after adding the ADO.NET entity data model.

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

ViewModels Folder

Next, let's add the ViewModels folder to the project and keep all the ViewModels in the same folder.

add viewmodel folder in asp.net mvc application

Adding CustomerVM to the ViewModels folder

Add a ViewModel named CustomerVM.cs to this folder. Click the ViewModels folder, select Add, and finally select Class as shown in

add new class in viewmodel folder in asp.net mvc
When you select a class, the Add New Item dialog box is displayed for this selected class, give name CustomerVM.cs.

give name to class file in asp.net mvc application

After adding the CustomerVM view model with the code shown below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TutorialViewModel.ViewModels
{
public class CustomerVM
{

}
}
Let's see the domain model entity we 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 the entity, let's add the properties of both models to the CustomerVM class. I got the name, address, mobile number from the customer model, got the order date and price from the order model, and displayed them in the 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) added controller with Name CustomerOrderDetails.

Add a Controller in Application

To add a controller, right-click the Controllers folder and select Add> Controller.

add new controller in asp.net mvc application

When you select a controller, a new dialog "Add Controller" is displayed. In this dialog, add the name "CustomerOrderDetailsController", select "Empty MVC Controller" in the template, and click the "Add" button.

give name to controller in viewmodel asp.net mvc application

After adding the controller "CustomerOrderDetailsController" containing the code 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)

Then write the code in this controller to get the value from the database and populate the ViewModel (CustomerVM) with the data

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

This controller gets the data from the database, joins both tables with (CustomerID), saves it in (CustomerList), applies a foreach loop to get this data in (List CustomerVMlist), and finally I have created a linq query to send and display to view

Add View to your application

To add a view, right-click the Index ActionResult method and select Add View to create a view template for the index form. In the snapshot below, we will create a strongly typed View with the View engine selected as the Razor and the CustomerVM model class selected, and a List form with the List selected in the Scaffold template. Finally, click the Add button.

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

Folder structure

after add view our viewmodel asp.net mvc project structure

Index.cshtml View 

Adding the view will generate the complete code for Index.cshtml below.

@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 view generated above, we have data from both the Customer model and the Order model, we saved the data in the CustomerVM (ViewModel) and displayed it at the end. Both the customer table and the order table contain the data shown below

tables data in asp.net mvc applicaiton

Then run the application and enter a URL like http: // localhost: ##### / CustomerOrderDetails / index to access the page.

Output:

output of viewmodel data in asp.net mvc application

.net mvc is easy to use and always uses ViewModels to clarify in information how to display the data and how to get the input data from different domain models.
Therefore, you can create a view model in asp.net mvc and use it in your mvc application if you want.

RAJESH GAMI - Blog

Digital Signature Pad in Angular | RAJESH GAMI

  What is Signature Pad? Signature Pad could be a JavaScript library for drawing fancy signatures. It supports HTML5 canvas and uses variabl...