English 中文(简体)
ASP.NET MVC - Data Model
  • 时间:2024-11-05

ASP.NET MVC - Data Model


Previous Page Next Page  

In this chapter, we will discuss about building models in an ASP.NET MVC Framework apppcation. A model stores data that is retrieved according to the commands from the Controller and displayed in the View.

Model is a collection of classes wherein you will be working with data and business logic. Hence, basically models are business domain-specific containers. It is used to interact with database. It can also be used to manipulate the data to implement the business logic.

Let’s take a look at a simple example of Model by creating a new ASP.Net MVC project.

Step 1 − Open the Visual Studio. Cpck File → New → Project menu option.

A new Project dialog opens.

Open the Visual Studio

Step 2 − From the left pane, select Templates → Visual C# → Web.

Step 3 − In the middle pane, select ASP.NET Web Apppcation.

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

MVCSimpleApp

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

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

We need to add a controller now.

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

It will display the Add Scaffold dialog.

Right-cpck 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 pst other methods pke Edit/Delete/Create as well.

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

Add Employee Controller

Step 9 − Set the name to EmployeeController and cpck the ‘Add’ button.

Step 10 − You will see a new C# file ‘EmployeeController.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 MVCSimpleApp.Controllers {
   pubpc class EmployeeController : Controller{
      // GET: Employee
      pubpc ActionResult Index(){
         return View();
      }
		
      // GET: Employee/Details/5
      pubpc ActionResult Details(int id){
         return View();
      }
		
      // GET: Employee/Create
      pubpc ActionResult Create(){
         return View();
      }
		
      // POST: Employee/Create
      [HttpPost]
      pubpc ActionResult Create(FormCollection collection){
         try{
            // TODO: Add insert logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: Employee/Edit/5
      pubpc ActionResult Edit(int id){
         return View();
      }
		
      // POST: Employee/Edit/5
      [HttpPost]
      pubpc ActionResult Edit(int id, FormCollection collection){
         try{
            // TODO: Add update logic here
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: Employee/Delete/5
      pubpc ActionResult Delete(int id){
         return View();
      }
		
      // POST: Employee/Delete/5
      [HttpPost]
      pubpc 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-cpck on the Models folder in the solution explorer and select Add → Class.

Right-cpck Models Folder

You will see the Add New Item dialog.

Add New Item Dialog

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

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


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

namespace MVCSimpleApp.Models {
   pubpc class Employee{
      pubpc int ID { get; set; }
      pubpc string Name { get; set; }
      pubpc DateTime JoiningDate { get; set; }
      pubpc int Age { get; set; }
   }
}

Let’s update the EmployeeController.cs file by adding one more method, which will return the pst of employee.


[NonAction]
pubpc List<Employee> GetEmployeeList(){
   return new List<Employee>{
      new Employee{
         ID = 1,
         Name = "Allan",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 23
      },
		
      new Employee{
         ID = 2,
         Name = "Carson",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 45
      },
		
      new Employee{
         ID = 3,
         Name = "Carson",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 37
      },
		
      new Employee{
         ID = 4,
         Name = "Laura",
         JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
         Age = 26
      },
   };
}

Step 14 − Update the index action method as shown in the following code.


pubpc ActionResult Index(){
   var employees = from e in GetEmployeeList()
   orderby e.ID
   select e;
   return View(employees);
}

Step 15 − Run this apppcation and append /employee to the URL in the browser and press Enter. You will see the following output.

Can t Find Index View

As seen in the above screenshot, there is an error and this error is actually quite descriptive which tells us it can t find the Index view.

Step 16 − Hence to add a view, right-cpck inside the Index action and select Add view.

Right-cpck Index Action

It will display the Add View dialog and it is going to add the default name.

Add Default Name

Step 17 − Select the List from the Template dropdown and Employee in Model class dropdown and also uncheck the ‘Use a layout page’ checkbox and cpck ‘Add’ button.

It will add some default code for you in this view.


@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
   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.JoiningDate)
            </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.JoiningDate)
               </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>

Step 18 − Run this apppcation and you will receive the following output.

List of Employees

A pst of employees will be displayed.

Advertisements