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.

How to work Area in MVC || RAJESH GAMI






Working with Area

Basically, Area are used to better manage large projects. For example, you might have an e-commerce application with admins, shops, billing sections, and admins managing back-end tasks such as creating categories, catalogs, prices, and so on. The store is an end-user portal for searching, which you add to your cart selection and where billing is done and delivery is managed.
 
As you can see, each of these sections is functionally very large and can be easily divided into sections. Let's see how to start from the Area.

Add an area in a MVC project

1. In the new MVC4 application, right-click on the project and select Add> Area

add-area

2. Name the Area ‘Admin’

3. This will create an Areas folder  with the following hierarchy added to your project

new-area-folder-hierarchy

4. AdminAreaRegistration.cs file. The generated class looks like this

public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
  get
  {
   return "Admin";
  }
}
public override void RegisterArea(AreaRegistrationContext context)
{
  context.MapRoute(
   "Admin_default",
   "Admin/{controller}/{action}/{id}",
   new { action = "Index", id = UrlParameter.Optional }
   );
}
}

As you can see from the class, it derives from the AreaRegistration class and overrides the AreaName  and  RegisterArea properties. 

a. AreaName returns the name you specified when you created the area. 

b. RegisterArea registers a new route for an area that begins with "Admin" (the name of the area) by calling the MapRoute method of the context. 

5. Next, let's open Global.asax and check the order of the routes. Note that AreaRegistration.RegisterAllAreas () is called before RouteConfig.RegisterRoutes (). This basically means  that the above route is registered before the default ASP.NET root is installed. This is important because you can call / HomeController / Index / and / Admin / HomeController / Index. If / HomeController / Index is registered first, navigation to / Admin / HomeController / Index will be redirected to the wrong controller class.


protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}

Now that we've added a new area, let's add a controller and a view. Also call the  controller HomeController in the new area to test the routing. 

add-controller

Next, add a new view named Index to the Areas \ Admin \ View \ Home folder, add _ViewStart.cshtml to the Areas \ Admin \ View \ folder, and add the Areas \ Admin \ View \ Shared folder. Add _Layout.cshtml. .. 

adding-views

@{
    ViewBag.Title = "Index";
}

<h2>Areas\Home\Index</h2>
Listing 3 Index.cshtml

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Listing 4 _ViewStart.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Admin Area</title>
</head>
<body>
<h1>Admin Area</h1>
<div>
  @RenderBody()
</div>
</body>
</html>

Listing 5 _Layout.cshtml

 Now let's run the application. Before you reach the home page, it will be the next YSoD (Yellow Screen of Death).

multiple-controller-ysod

Don't you like the redundancy of exceptions? In plain language, this means: If you  have two controllers named HomeController, you need to specify their namespace when you register the route.

The AreaRegistrationContext is said to have used the namespace when registering the route with the RegisterArea method  we saw earlier. This leaves a default route registration with no namespace defined. Go to App_Start \ RouteConfig.cs and add the Namespaces parameter to your MapRoute method call. Pass the MvcAreasDemo.Controllers namespace as a parameter of the default HomeController.

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}/{id}",
  defaults: new {
   controller = "Home",
   action = "Index",
   id = UrlParameter.Optional },
   // add the explicit namespaces param when using Areas
   namespaces: new [] { "MvcAreasDemo.Controllers" }
);
}

  

Default MVC launch page

default-view-one-aread

Now when you go to the admin / home URL, you'll see that the home controller in the admin panel is working. 

Adding another Area

Now that the new scope has been added  and is working fine, how can I tell if the second scope is causing a  routing conflict? Now, as mentioned earlier, the AreaRegistrationContext internally passes the NameSpace to the root configuration. Therefore, multiple areas registered via the AreaRegistrationContext do not cause any problems. For your safety, add another scope called Store and add a HomeController  (do not copy from the admin scope or create a subclass between the admin scope and the store scope). You can copy the view and update it accordingly. 
Run the  application and go to all  three HomeControllers to view the pages individually.

 default-view-two-areas

Conclusion

In summary, sections are a useful configuration when trying to build a large front-end system with well-separated functional sections. The only problem is that controllers with the same name in scope must have different namespaces, and the default route (if used)  explicitly provides namespace parameters during controller configuration. That's what you need to do.


Set route as shown below into RouteConfig.cs file

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

namespace CableSoft
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new {area="Admin",controller = "Login", action = "Index", id = UrlParameter.Optional }
            ).DataTokens.Add("area""Admin");
        }
    }
}

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