Data model in asp.net MVC

In this chapter, we’ll discuss concerning building models in  ASP.NET MVC Framework application. A model stores knowledge that’s retrieved in keeping with the commands from the Controller and displayed within the read.

Model may be a assortment of categories whereby you may be operating with knowledge and business logic. Hence, essentially models ar business domain-specific containers. it’s accustomed move with info. It may be accustomed manipulate the info to implement the business logic.

Let’s take a glance at an easy example of read by making a brand new ASP.Net MVC project.

Step 1− Open the Visual Studio. Click File → New → Project menu possibility..

Open the Visual Studio
Step 2− From the left pane, choose Templates → Visual C# → internet.

Step 2− within the middle pane, select ASP.NET internet Application.

Step 4 − Enter the project name ‘MVCDataModelDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.

MVCDataModelDemo
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.

It will create a basic MVC project with minimal predefined content.

We need to add a controller now.

Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller.

Right-click Controller Folder
Step 7 − Select the MVC 5 Controller – with read/write actions option. This template will create an Index method with default action for Controller. This will also list other methods like Edit/Delete/Create as well.

Step 8 − Click ‘Add’ button and Add Controller dialog will appear.

Add User Controller
Step 9 − Set the name to UserController and click the ‘Add’ button.

Step 10 − You will see a new C# file ‘UserController.cs’ in the Controllers folder, which is open for editing in Visual Studio with some default actions.

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

using System.Web;
using System.Web.Mvc;

namespace MVCDataModelDemo.Controllers {
   public class UserController : Controller{
      // GET: User
      public ActionResult Index(){
         return View();
      }
		
      // GET: User/Details/5
      public ActionResult Details(int id){
         return View();
      }
		
      // GET: User/Create
      public ActionResult Create(){
         return View();
      }
		
      // POST: User/Create
      [HttpPost]
      public ActionResult Create(FormCollection collection){
         try{
            // TODO: Add insert logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: User/Edit/5
      public ActionResult Edit(int id){
         return View();
      }
		
      // POST: User/Edit/5
      [HttpPost]
      public ActionResult Edit(int id, FormCollection collection){
         try{
            // TODO: Add update logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: User/Delete/5
      public ActionResult Delete(int id){
         return View();
      }
		
      // POST: User/Delete/5
      [HttpPost]
      public ActionResult Delete(int id, FormCollection collection){
         try{
            // TODO: Add delete logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
   }
}

Let’s add a model.

Step 11 − Right-click on the Models folder in the solution explorer and select Add → Class.

Right-click Models Folder

Step 12 − Select Class in the middle pan and enter User.cs in the name field.

Step 13 − Add some properties to User class using the following code.

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

namespace MVCDataModelDemo.Models {
   public class User{
      public int ID { get; set; }
      public string Name { get; set; }
      public DateTime DateofBirth { get; set; }
      public int Age { get; set; }
   }
}

Let’s update the UserController.cs file by adding another methodology, which is able to come the list of worker.

[NonAction]
public List<User> GetUserList(){
   return new List<User>{
      new User{
         ID = 1,
         Name = "Pawan",
         DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
         Age = 23
      },
		
      new User{
         ID = 2,
         Name = "Diwakar",
         DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
         Age = 45
      },
		
      new User{
         ID = 3,
         Name = "Rohit",
         DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
         Age = 37
      },
		
      new User{
         ID = 4,
         Name = "Pushpraj",
         DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
         Age = 26
      },
   };
}

Step fourteen − Update the index action methodology as shown within the following code.

public ActionResult Index(){
   var users = from e in GetUserList()
   orderby e.ID
   select e;
   return View(users);
}

Step 15− Run this application and append /User to the uniform resource locator within the browser and press Enter. you may see the subsequent output.

Can’t realize Index read
As seen within the higher than screenshot, there’s miscalculation and this error is truly quite descriptive that tells United States it cannot realize the Index read.

Step 16− thence to feature a read, right-click within the Index action and choose Add read.

Right-click Index Action
It will show the Add read dialog and it’s progressing to add the default name.

Add Default Name
Step 17− choose the List from the guide dropdown and worker in Model category dropdown and conjointly uncheck the ‘Use a layout page’ checkbox and click on ‘Add’ button.

@model IEnumerable<MVCDataModelDemo.Models.User>
@{
   Layout = null;
}

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>Index</title>
   </head>
	
   <body>
      <p>@Html.ActionLink("Create New", "Create")</p>
         <table class = "table">
         <tr>
            <th>
               @Html.DisplayNameFor(model => model.Name)
            </th>
				
            <th>
               @Html.DisplayNameFor(model => model.DateofBirth)
            </th>
				
            <th>
               @Html.DisplayNameFor(model => model.Age)
            </th>
				
            <th></th>
         </tr>
			
         @foreach (var item in Model) {
            <tr>
               <td>
                  @Html.DisplayFor(modelItem => item.Name)
               </td>
					
               <td>
                  @Html.DisplayFor(modelItem => item.DateofBirth)
               </td>
					
               <td>
                  @Html.DisplayFor(modelItem => item.Age)
               </td>
					
               <td>
                  @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                  @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                  @Html.ActionLink("Delete", "Delete", new { id = item.ID })
               </td>
					
            </tr>
         }
			
      </table>
   </body>
</html>

It will add some default code for you during this read.
Step 18− Run this application and you may receive the subsequent output.

List of users
A list of staff are going to be displayed.

Leave a Reply

Your email address will not be published. Required fields are marked *