Thứ Ba, 6 tháng 12, 2016

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 represent only the data we want to display on view 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 then we need to create a new viewmodel. Following image shows visual representation of 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 have look on table which we are going to use in our application.


Database Part

In this database part we will create required tables in database with 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 above script it will create Customer table like as shown below

Customer Table in Database in sql server

Order table

Following is the script to create 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 new asp.net mvc 4 application for that Open visual studio studio àGo to File à Select New à Select Project

create new asp.net mvc project from visual studio 2012

After that you will see new dialog will pop up 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 and here we are giving name as “TutorialViewModel” then finally click on ok button

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

After naming it just click on OK now new dialog will pop up for selecting 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 just right click on your application and from the list select "Manage NuGet Packages"

install entity framework in asp.net mvc application

After select a new dialog will popup of “Manage NuGet Packages” inside search box enter “EntityFramework”. After getting search value select EntityFramework click on 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 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 just 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 OK button.

customerorderdb entity name in asp.net mvc application
After that a new Wizard will popup where we are going configure 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 Next button. After clicking on 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 a 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 User name and Password of Sql server. Last we are going to select Database Name "OrderDB" once we done click on OK button as shown below

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

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

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

 Now click on Next button. A new wizard will popup for selecting database object and in this we will see all the table which we have created in database.

select order table from database in asp.net mvc

And last click on Finish button. Here is 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 project for keeping all ViewModel in 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 just 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 class then Add New Item dialog will popup in that select class and give 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 add

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. In this 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 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 controller a new Add Controller Dialog will popup in that just add Name CustomerOrderDetailsController and in template select Empty MVC Controller and click on 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)

Now inside this Controller let’s write code for getting values from 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 wrote a Linq query for getting data from database with join both tables with  (CustomerID) and stored it in  ( customerlist) and then applying foreach loop for pushing that data into (List<CustomerVM> CustomerVMlist ) and lastly sending it to View.

Adding View in Application

For Adding View just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in below snapshot we selected View engine as Razor and we are going to create a strongly type view for that we selected Model class CustomerVM and 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 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 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 view. Our both tables Customer and Order contains data like as shown below

tables data in asp.net mvc applicaiton

Now just run application and access page by entering 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.
Donate: http://tutlane.com/tutorial/aspnet-mvc/how-to-use-viewmodel-in-asp-net-mvc-with-example

Không có nhận xét nào :

Đăng nhận xét