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.
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,)
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 >ProjectAfter 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.
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.
After building the application, this is the complete folder view.
Installing Entity Framework on your application
To add Entity Framework, right-click on the application and select Manage NuGet Packages from the list.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.
After adding a green OK symbol will be displayed.
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.Enter any name, but it must be unique and click the OK button.
Then you will see a new wizard that configures the entity data model. In this case, use database first.
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
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.
After adding the database connection, the Entity Data Model Wizard looks like this:
A new wizard for selecting database objects is displayed, showing all the tables you have created in the database.
Finally, click the Finish button. This is a snapshot after adding the ADO.NET entity data model.
ViewModels Folder
Next, let's add the ViewModels folder to the project and keep all the ViewModels in the same folder.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 inWhen you select a class, the Add New Item dialog box is displayed for this selected class, give name CustomerVM.cs.
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
{
}
}
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
}
}
Add a Controller in Application
To add a controller, right-click the Controllers folder and select Add> Controller.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.
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)
}
}
}
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.Folder 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>
Then run the application and enter a URL like http: // localhost: ##### / CustomerOrderDetails / index to access the page.
Output:
.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.