Introduction to Models in ASP.NET MVC
A view is the content of a webpage that displays in a browser. When it comes to how a view is populated, there are two categories: static and dynamic…
Models Fundamentals#
Introducing a View#
A view is the content of a webpage that displays in a browser. When it comes to how a view is populated, there are two categories: static and dynamic webpages. A static webpage is a view that displays content that doesn't change. The webpage is created as a computer file. To get the document, the visitor can type the file location in the address bar of a browser or use a search engine to find the document. A dynamic webpage falls in two categories. One type of a dynamic webpage is a document that is partially created. Additional processing can be performed to complete the webpage. For example, a visitor can enter some values in a webform and click a button. Some calculations can then be performed and the webpage would be updated with new values. The second category of dynamic webpage is a document that doesn't currently exist on the webserver. To get the document, the user must request it one way or another. For example, using a form on a certain webpage, the user can provide one or more values and submit them to the webserver (probably by clicking a button). The webserver would then create the document and display in in the browser. As another example, the user may request to print a document, the webserver creates the graphic to print and displays it in the browser. In most cases, the document is created and displayed in the browser but once the visitor moves away or closes the browser, the document disappears, which means it cannot be found again; it would have to be recreated. Such a document lasts for the duration of the session. You can create a dynamic webpage on the view or else. The views of an ASP.NET MVC project are created in a folder named Views. Practical Learning: Introducing Views
- On the main menu of Microsoft Visual Studio, click File -> New -> Project...
- In the middle frame of the New Project dialog box, click ASP.NET Web Application (.NET Framework). Change the project Name to TireDirect3
- Click OK
- In the New ASP.NET Web Application dialog box, click the MVC icon and click OK
- In the Solution Explorer, right-click TireDirect3 -> Add -> New Folder
- Type Images and press Enter
- Save the following graphic to the Images folder:
- In the Solution Explorer, right-click Content -> Add New -> Item...
- In the left frame of the Add New Item dialog box, click Web. In the middle frame, click Style Sheet
- Change the file Name to TireDirect
- Click Add
- Create some styles as follows: body { background-color: #C7DFF6; } .navbar { background-color: #003366; } .navbar-fixed-top { border-bottom: 6px solid #000; } .topbar { top: 0; width: 100%; height: 16em; position: fixed; background-color: #124386; border-bottom: 4px solid #000000; } .tires-container { margin: auto; height: 220px; width: 715px; border: 4px solid #000; background-image: url("../Images/td1.png"); } .jumbotron { padding-top: 30px; padding-bottom: 10px; background-color: #0d5294; } .jumbotron h1 { text-align: center; color: #C7DFF6; } .lead { color: #C7D6E4; } .col-md-4 h2 { color: navy; } .copyright { color: wheat; text-align: center; } .GroupBox { border-radius: 5px; padding-left: 20px; padding-right: 20px; width: 315px; background-color: #7EAFF2; border: 2px solid navy; } .empl-details-group { border-radius: 5px; padding-left: 20px; padding-right: 20px; width: 335px; background-color: #7EAFF2; border: 2px solid navy; } .left-col { width: 135px; } .centralized { margin: auto; width: 400px; } .accent { font-weight: 600; } .GroupBox legend, .empl-details-group legend { border-radius: 3px; margin-left: 10px; font-size: 16px; width: 235px; color: #E5DDAF; background-color: #0d5294; padding: 3px 15px; box-shadow: 0 0 0 5px black; } .GroupBox table, .empl-details-group table { margin-bottom: 15px; margin-left: 15px; } .navbar-inverse .navbar-brand { color: #FFF; } .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus { color: #d8d553; } .navbar-inverse .navbar-nav > li > a { color: #FFF; } .navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus { color: #d8d553; } .container .jumbotron { border-radius: 1px; border-bottom-left-radius: 16px; border-bottom-right-radius: 16px; }
- In the Solution Explorer, under Views, expand Home
- Double-click Index.cshtml to open it
- Change the document as follows: @{ ViewBag.Title = "Welcome to Tire Direct"; } <div class="jumbotron"> <div class="tires-container"> </div> <h1>Tire Direct</h1> <p class="lead"> At Tire Direct, we install tires on all types of vehicles, for all seasons, under every circumference. Visit one or our many locations. Check our equipment. Meet our staff. Our service is money-back guaranteed. </p> <p class="text-center"><a href="/Home/Index" class="btn btn-primary btn-lg">Visit One of Our Locations »</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Tire Installation</h2> <p> Our service is fast. Our staff is friendly and professional. Our rates are competitive. </p> <p><a class="btn btn-primary" href="/Home/Index">Schedule an Appointment »</a></p> </div> <div class="col-md-4"> <h2>Tire Installation/Rates</h2> <p>Our tire installation rates are very competitive compared to other shops.</p> <p>@Html.ActionLink("Start Tire Installation " + Server.HtmlDecode("»"), "PayrollStartUp", "PayrollManagement", null, new { @class = "btn btn-primary" })</p> </div> <div class="col-md-4"> <h2>Employees Portal</h2> <p> This is the place for employees to check email, payroll, benefits, requests for time off, etc. </p> <p>@Html.ActionLink("Hire Employee " + Server.HtmlDecode("»"), "Create", "PayrollManagement", null, new { @class = "btn btn-primary" })</p> </div> </div>
Introducing a Controller#
One way to create a dynamic webpage is to do most or all of the processing on the webserver. To do this, create a special class called a controller. One of the jobs of a controller is to organize a website in sections called actions. Each action takes care of a particular detail. The controllers of a website are created in a folder named Controllers. The view and the controller have this in common. Both can do some processing. For example, a view by itself can get some values from a visitor, perform some calculations, and present the values in a browser. A view can receive some values, send them to a controller that would perform the necessary calculations, and send back the results to the view that would present those values to the visitor. Alternatively, a controller can receive some values, perform some calculations partially, send them to the view that would do some additional processing before displaying the result(s). One of the differences between a view and a controller is that a view is a normal computer document while a controller is a class, not a document. Practical Learning: Creating a Controller
- In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
- In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller - Empty
- Click Add
- Type PayrollManagement to get PayrollManagementController
- Click Add
Introducing a Model#
One of the characteristics of a website is that it (may) use(s) a section, as a repository of data, in a webserver. That repository of data is used to hold or store some values of objects. For this reason, that repository of data is called a database. A data repository (a database) can hold any type of data. It is up to you depending on the type of website you are creating. A model is a document that contains instructions that allow communication between a controller and data on a webserver. ASP.NET MVC supports various ways to create, use, and manage models.
Starting a Model#
Introducing a Model Class#
A model, or rather a model class, is a class that represents the data stored in a webserver. Therefore, to start a model, create a class. That class is like any of the classes we have created in previous lessons. The class can represent an employee, a customer, an item sold in a store, a time sheet, a TV show, a survey result, anything you want. In an ASP.NET MVC project, models are created in a folder named Models. If you create a project in Microsoft Visual Studio, the studio would create the Models folder for you. To get a model class, create the class in the Models folder. Practical Learning: Starting a Model
- In the Solution Explorer, right-click Models -> Add -> Class...
- Change the Name to Employee
- Click Add
- Complete the class as follows: namespace TireDirect3.Models { public class Employee { public long EmployeeNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
- In the Solution Explorer, right-click Models -> Add -> Class...
- Change the Name to Payroll
- Click Add
- Complete the class as follows: namespace TireDirect3.Models { public class Payroll { public int PayrollNumber { get; set; } public long EmployeeNumber { get; set; } public double BaseHourlyRate { get; set; } public double BaseTireRate { get; set; } public int MondayInstallations { get; set; } public double MondayPay { get; set; } public int TuesdayInstallations { get; set; } public double TuesdayPay { get; set; } public int WednesdayInstallations { get; set; } public double WednesdayPay { get; set; } public int ThursdayInstallations { get; set; } public double ThursdayPay { get; set; } public int FridayInstallations { get; set; } public double FridayPay { get; set; } public double NetPay { get; set; } } }
- In the Solution Explorer, right-click Models -> Add -> Class...
- Change the Name to Collection
- Click Add
- Complete the class as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TireDirect3.Models { public class Collection <T> : IEnumerable<T> { private T[] items; private int size; public Collection() { size = 0; items = new T[10]; } public int Count { get { return size; } } public void Add(T number) { items[size] = number; size++; } public T this[int index] { get { return items[index]; } set { items[index] = value; size++; } } public IEnumerator<T> GetEnumerator() { int counter = 0; while (counter < Count) { yield return items[counter]; counter++; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { int counter = 0; while (counter < Count) { yield return items[counter]; counter++; } } } }
- In the Solution Explorer, below Controllers, double-click PayrollManagementController.cs to open it
- Change the document as follows: using System.Web.Mvc; namespace TireDirect3.Controllers { public class PayrollManagementController : Controller { // This is a fixed list of employees used in this appl ication. // We are creating it here because we will not do any file processing in this project public Models.Employee[] Employees = new Models.Employee[] { new Models.Employee() { EmployeeNumber = 928547, FirstName = "Robert", LastName = "Simpson" }, new Models.Employee() { EmployeeNumber = 294708, FirstName = "Gabrielle", LastName = "Leighton" }, new Models.Employee() { EmployeeNumber = 529485, FirstName = "Peter", LastName = "Cotton" }, new Models.Employee() { EmployeeNumber = 135170, FirstName = "Jennifer", LastName = "Gallagher" } }; // This is a variable that will hold the list of payrolls for this project. Models.Collection<Models.Payroll> Payrolls = new Models.Collection<Models.Payroll>(); // GET: PayrollManagement public ActionResult Index() { return View(); } // GET: PayrollManagement/LoanContractStartUp public ActionResult PayrollStartUp() { return View(); } public ActionResult PayrollPreparation(FormCollection collection) { double payRate = 0.00; double tireRate = 0.00; double dailySalary = 0.00; long strEmployeeNumber = 0; double dInstallationMondayPay = 0.00; double dInstallationTuesdayPay = 0.00; double dInstallationWednesdayPay = 0.00; double dInstallationThursdayPay = 0.00; double dInstallationFridayPay = 0.00; if (!string.IsNullOrEmpty(collection["EmployeeNumber"])) { ViewBag.PayrollNumber = collection["PayrollNumber"]; try { ViewBag.EmployeeNumber = collection["EmployeeNumber"]; strEmployeeNumber = Convert.ToInt64(collection["EmployeeNumber"]); var staff = from empl in Employees where empl.EmployeeNumber == strEmployeeNumber select new { FirstName = empl.FirstName, LastName = empl.LastName, }; if (staff != null) { foreach (var clerk in staff) { ViewBag.FirstName = clerk.FirstName; ViewBag.LastName = clerk.LastName; } } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid employee number."; } try { if (!string.IsNullOrEmpty(collection["BaseHourlyRate"])) { ViewBag.BaseHourlyRate = collection["BaseHourlyRate"]; payRate = double.Parse(collection["BaseHourlyRate"]); dailySalary = payRate * 8.00; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid base hourly rate."; } try { if (!string.IsNullOrEmpty(collection["BaseTireRate"])) { ViewBag.BaseTireRate = collection["BaseTireRate"]; tireRate = double.Parse(collection["BaseTireRate"]); } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid rate (cost) for a tire installation."; } try { if (!string.IsNullOrEmpty(collection["MondayInstallations"])) { ViewBag.MondayInstallations = collection["MondayInstallations"]; dInstallationMondayPay = int.Parse(collection["MondayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Monday."; } try { if (!string.IsNullOrEmpty(collection["TuesdayInstallations"])) { ViewBag.TuesdayInstallations = collection["TuesdayInstallations"]; dInstallationTuesdayPay = int.Parse(collection["TuesdayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Tuesday."; } try { if (!string.IsNullOrEmpty(collection["WednesdayInstallations"])) { ViewBag.WednesdayInstallations = collection["WednesdayInstallations"]; dInstallationWednesdayPay = int.Parse(collection["WednesdayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Wednesday."; } try { if (!string.IsNullOrEmpty(collection["ThursdayInstallations"])) { ViewBag.ThursdayInstallations = collection["ThursdayInstallations"]; dInstallationThursdayPay = int.Parse(collection["ThursdayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Thursday."; } try { if (!string.IsNullOrEmpty(collection["FridayInstallations"])) { ViewBag.FridayInstallations = collection["FridayInstallations"]; dInstallationFridayPay = int.Parse(collection["FridayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Friday."; } double dMondayNetPay = dInstallationMondayPay; double dTuesdayNetPay = dInstallationTuesdayPay; double dWednesdayNetPay = dInstallationWednesdayPay; double dThursdayNetPay = dInstallationThursdayPay; double dFridayNetPay = dInstallationFridayPay; if (dInstallationMondayPay < dailySalary) { dMondayNetPay = dailySalary; } if (dInstallationTuesdayPay < dailySalary) { dTuesdayNetPay = dailySalary; } if (dInstallationWednesdayPay < dailySalary) { dWednesdayNetPay = dailySalary; } if (dInstallationThursdayPay < dailySalary) { dThursdayNetPay = dailySalary; } if (dInstallationFridayPay < dailySalary) { dFridayNetPay = dailySalary; } ViewBag.MondayNetPay = dMondayNetPay.ToString("F"); ViewBag.TuesdayNetPay = dTuesdayNetPay.ToString("F"); ViewBag.WednesdayNetPay = dWednesdayNetPay.ToString("F"); ViewBag.ThursdayNetPay = dThursdayNetPay.ToString("F"); ViewBag.FridayNetPay = dFridayNetPay.ToString("F"); ViewBag.NetPay = (dMondayNetPay + dTuesdayNetPay + dWednesdayNetPay + dThursdayNetPay + dFridayNetPay).ToString("F"); } return View(); } } }
- In the document, right-click inside the PayrollStartUp() method and click Add View...
- In the dialog box, make sure the text box is displaying PayrollStartUp and click Add
- Change the document as follows: @{ ViewBag.Title = "Payroll Start-Up"; } <h2>Payroll Start Up</h2> <hr /> @using (Html.BeginForm("PayrollPreparation", "PayrollManagement", FormMethod.Post)) { <table> <tr> <td><b>Employee #:</b></td> <td>@Html.TextBox("EmployeeNumber")</td> </tr> <tr> <td><b>Base Hourly Rate:</b></td> <td>@Html.TextBox("BaseHourlyRate", "12.50")/Hr</td> </tr> <tr> <td><b>Base Tire Rate:</b></td> <td>@Html.TextBox("BaseTireRate", "1.15")/Tire</td> </tr> </table> <hr /> <fieldset class="GroupBox"> <legend>Number of Tires Installed on</legend> <table> <tr> <td><b>Monday:</b></td> <td>@Html.TextBox("MondayInstallations", "0")</td> </tr> <tr> <td><b>Tuesday:</b></td> <td>@Html.TextBox("TuesdayInstallations", "0")</td> </tr> <tr> <td><b>Wednesday:</b></td> <td>@Html.TextBox("WednesdayInstallations", "0")</td> </tr> <tr> <td><b>Thursday:</b></td> <td>@Html.TextBox("ThursdayInstallations", "0")</td> </tr> <tr> <td><b>Friday:</b></td> <td>@Html.TextBox("FridayInstallations", "0")</td> </tr> </table> </fieldset> <hr /> <p></p> <table> <tr> <td><b>Payroll #:</b> @Html.TextBox("PayrollNumber")</td> <td><input type="submit" name="btnPreparePayroll" value="Prepare Payroll" style="width: 150px" /></td> </tr> </table> }
An Action to Request Data#
As seen so far in previous lessons, if you want visitors to give you values necessary to build an object, you may need to create a view. Of course, you should start by creating an action method. The method can be named Create because it is used to create an object. Here is an example of such a method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Exercises.Controllers
{
public class PersonnelController : Controller
{
// GET: Personnel
public ActionResult Index()
{
return View();
}
// GET: Personnel/Create
public ActionResult Create()
{
return View();
}
}
}After doing this, you can create a view of the same name. Practical Learning: Adding a Creation View
- Click the PayrollManagementController.cs to access it and create a method named Create as follows: using System.Web.Mvc; namespace TireDirect3.Controllers { public class PayrollManagementController : Controller { . . . No Change public ActionResult Create() { return View(); } } }
- In the document, right-click inside the Create() method and click Add View...
- In the dialog box, make the text box displays Create as the name of the view and click Add @{ ViewBag.Title = "Create"; } <h2>Create</h2>
An Action to Relay Data#
One of the jobs of a model, in fact its main jobs, is to act as an intermediary between a controller and the data repository. If the data will be provided by a visitor of your website (for example through a webform), you should (must) create a controller action to get the data from the view (the webpage) to the data repository. To connect the view to the relaying action, the action method must use the same name as the action of the view. In this case, the action is named Create. Here is an example:
using System.Web.Mvc;
namespace Exercises.Controllers
{
public class PayrollManagementController : Controller
{
. . . No Change
public ActionResult Create()
{
return View();
}
public ActionResult Create()
{
return View();
}
}
}(Notice that this code creates a name confilct because both methods have the exact same syntax). The job of this action is to get the object that should be sent to the data repository. For this reason, this method can take a parameter of the class that holds a record, which is the model class. As an alternative and as we saw in previous sections, since the method will use values of webcontrols from a form, the method can take a FormCollection argument. Practical Learning: Creating an Action to Relay Data
- Access the PayrollManagementController.cs file and create an action method named Create that takes a parameter of type Payroll as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TireDirect3.Controllers { public class PayrollManagementController : Controller { . . . No Change public ActionResult Create() { return View(); } public ActionResult Create(Models.Payroll payroll) { return View(); } } }
Adding an Object to a Data Repository#
Once an object has been created (for example using values gotten from a webform), usually from a view, and the object is passed to the second Create() method as argument, in that Create() method, you can call the method (normally from a collection class; the method is usually named Add) that would add the object to the data repository. Here is an example:
using System.Web.Mvc;
namespace TireDirect3.Controllers
{
public class PersonnelController : Controller
{
Models.Collection<Models.Employee> Employees = new Models.Collection<Models.Employee>();
// GET: Personnel
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
public ActionResult Create(Models.Employee staff)
{
Employees.Add(staff);
return View();
}
}
}After doing this, the Create() method can get the object and add it. If the Create view is also used to create the object, you can simply add a Submit button to it and that would work. Here is an example:
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
<p><input type="submit" /></p>
}If another view is used to create the object, you can (should/must) pass a Create string as the first argument to the Html.BeginForm() method. Practical Learning: Adding an Object to a Data Repository
- Change the method as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TireDirect3.Controllers { public class PayrollManagementController : Controller { . . . No Change public ActionResult Create() { return View(); } public ActionResult Create(Models.Payroll payroll) { Payrolls.Add(payroll); return View(); } } }
- In the document, right-click inside the PayrollPreparation() method and click Add View...
- In the dialog box, make sure the text box displays PayrollPreparation as the name of the view and click Add
- Change the document as follows: @{ ViewBag.Title = "Payroll Preparation"; string strErrorMessage = ViewBag.ErrorMessage; } <h2>Payroll Preparation</h2> <hr /> @using (Html.BeginForm("Create", "PayrollManagement", FormMethod.Post)) { <div class="row"> <div class="col-md-4"> <fieldset class="empl-details-group"> <legend>Employee Details</legend> <table> <tr> <td class="left-col accent">Employee #:</td> <td>@Html.TextBox("EmployeeNumber", ViewBag.EmployeeNumber as string, new { style = "width: 80px" })</td> <td> </td> </tr> <tr> <td class="accent">Employee Name:</td> <td>@Html.TextBox("FirstName", ViewBag.FirstName as string, new { style = "width: 80px" })</td> <td>@Html.TextBox("LastName", ViewBag.LastName as string, new { style = "width: 80px" })</td> </tr> </table> <table> <tr> <td class="left-col accent">Base Hourly Rate:</td> <td>@Html.TextBox("BaseHourlyRate", ViewBag.BaseHourlyRate as string, new { style = "width: 80px" })/Hr</td> </tr> <tr> <td class="accent">Base Tire Rate:</td> <td>@Html.TextBox("BaseTireRate", ViewBag.BaseTireRate as string, new { style = "width: 80px" })/Tire</td> </tr> </table> </fieldset> <hr /> <table> <tr> <td class="left-col accent"><b>Net Pay:</b></td> <td>@Html.TextBox("NetPay", ViewBag.NetPay as string)</td> </tr> <tr> <td class="accent">Payroll #:</td> <td>@Html.TextBox("PayrollNumber", ViewBag.PayrollNumber as string)</td> </tr> </table> </div> <div class="col-md-4"> <fieldset class="GroupBox"> <legend>Tires Installations</legend> <table> <tr> <td class="left-col"> </td> <td><b>Day</b></td> <td><b>Pay</b></td> </tr> <tr> <td><b>Monday:</b></td> <td>@Html.TextBox("MondayInstallations", ViewBag.MondayInstallations as string, new { style = "width: 80px" })</td> <td>@Html.TextBox("MondayPay", ViewBag.MondayNetPay as string, new { style = "width: 80px" })</td> </tr> <tr> <td><b>Tuesday:</b></td> <td>@Html.TextBox("TuesdayInstallations", ViewBag.TuesdayInstallations as string, new { style = "width: 80px" })</td> <td>@Html.TextBox("TuesdayPay", ViewBag.TuesdayNetPay as string, new { style = "width: 80px" })</td> </tr> <tr> <td><b>Wednesday:</b></td> <td>@Html.TextBox("WednesdayInstallations", ViewBag.WednesdayInstallations as string, new { style = "width: 80px" })</td> <td>@Html.TextBox("WednesdayPay", ViewBag.WednesdayNetPay as string, new { style = "width: 80px" })</td> </tr> <tr> <td><b>Thursday:</b></td> <td>@Html.TextBox("ThursdayInstallations", ViewBag.ThursdayInstallations as string, new { style = "width: 80px" })</td> <td>@Html.TextBox("ThursdayPay", ViewBag.ThursdayNetPay as string, new { style = "width: 80px" })</td> </tr> <tr> <td><b>Friday:</b></td> <td>@Html.TextBox("FridayInstallations", ViewBag.FridayInstallations as string, new { style = "width: 80px" })</td> <td>@Html.TextBox("FridayPay", ViewBag.FridayNetPay as string, new { style = "width: 80px" })</td> </tr> </table> </fieldset> </div> </div> <hr /> <p><input type="submit" name="btnSavePayroll" value="Save Payroll" style="width: 200px" /></p> <p>@strErrorMessage</p> }
The Responding Verb of an Action#
When creating an action that relays data from a view to a model, you must indicate how the action will get its HTTP requests. This information is held by an enumeration named HttpVerbs. The members of the HttpVerbs enumeration are Get, Post, Put, Head, Patch, Options, and Delete. To let you specify the verb that an action would use, ASP.NET MVC provides an attribute named AcceptVerbs from the AcceptVerbsAttribute class. To use it, you must apply this attribute to the action method. The AcceptVerbsAttribute class has two constructors. One of them used the following syntax:/p>
public AcceptVerbsAttribute(HttpVerbs verbs);This contructor takes an HttpVerbs member as argument. If you want to apply many verbs, you can use the other constructor. Practical Learning: Responding to a View
- Click the PayrollManagementController.cs tab to access it
- Change the document as follows: using System; using System.Linq; using System.Web.Mvc; namespace TireDirect32.Controllers { public class PayrollManagementController : Controller { . . . No Change public ActionResult Create() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Models.Payroll payroll) { Payrolls.Add(payroll); return View(); } } }
- In the Solution Explorer, expand Views and expand Shared
- Double-click _Layout.cshtml to open it
- Change the document as follows: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Tire Direct </title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") <link rel="stylesheet" type="text/css" href="~/Content/TireDirect.css" /> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink(" Tire Direct ", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Locations", "About", "Home")</li> <li>@Html.ActionLink("Vehicles", "Index", "Home")</li> <li>@Html.ActionLink("Accessories", "Index", "Home")</li> <li>@Html.ActionLink("Tires & Seasons", "About", "Home")</li> <li>@Html.ActionLink("Tire Selection", "Contact", "Home")</li> <li>@Html.ActionLink("Scenario", "About", "Home")</li> <li>@Html.ActionLink("FAQs", "Contact", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() </div> <div class="navbar navbar-inverse navbar-fixed-bottom"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Tools & Equipment", "About", "Home")</li> <li>@Html.ActionLink("Tire Parts", "Index", "Home")</li> <li>@Html.ActionLink("Cars", "Index", "Home")</li> <li>@Html.ActionLink("Motorcycles", "About", "Home")</li> <li>@Html.ActionLink("RVs", "About", "Home")</li> <li>@Html.ActionLink("Current Deals", "About", "Home")</li> <li>@Html.ActionLink("Tire Care", "Contact", "Home")</li> <li>@Html.ActionLink("Payroll Start-Up", "PayrollStartUp", "PayrollManagement")</li> <li>@Html.ActionLink("About Us", "About", "Home")</li> <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li> </ul> </div> </div> <hr /> <footer> <p class="copyright">© @DateTime.Now.Year - Tire Direct</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
- To execute the application, on the main menu, click Debug -> Start Without Debugging
- On the bottom menu, click the Payroll Start-Up link:
- In the text boxes, type the following values: Employee #: 529485 Base Hourly Rate: 11.26 Base Tire Rate: 1.08 Monday: 118 Tuesday 46 Wednesday: 125 Thursday: 52 Friday: 97 Payroll #: 100001
- Click the Prepare Payroll button
- Close the browser and return to your programming environment
Primary Characteristics of a Model#
A Model Object#
We saw that, to prepare a simple data repository, you can declare a variable of a collection class. Of course if you want the list to be accessible from many files, you should declare the variable outside of a method. We declared such a variable in the body of a controller class. To let you access such a variable, the WebViewPage class, which is the parent/type of a view, is equipped with a property named Model. The Model property is a collection. It holds a list of all the items in the collection variable previously created. To access the items of this property, use a foreach loop to access each member of the collection. Practical Learning: Accessing a Model
- In the Solution Explorer, below Controllers, double-click PayrollManagementController.cs to access it
- Create an action named PayrollSummary as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TireDirect3.Controllers { public class PayrollManagementController : Controller { // This is a fixed list of employees used in this application. // We are creating it here because we will not do any file processing in this project public Models.Employee[] Employees = new Models.Employee[] { new Models.Employee() { EmployeeNumber = 928547, FirstName = "Robert", LastName = "Simpson" }, new Models.Employee() { EmployeeNumber = 294708, FirstName = "Gabrielle", LastName = "Leighton" }, new Models.Employee() { EmployeeNumber = 529485, FirstName = "Peter", LastName = "Cotton" }, new Models.Employee() { EmployeeNumber = 135170, FirstName = "Jennifer", LastName = "Gallagher" } }; // This is a variable that will hold the list of payrolls for this project. // The "static" keyword is used so the records can be saved in memory while a user is creating records and using the website. // Such records will disappear once the session is over. public static Models.Collection<Models.Payroll> Payrolls = new Models.Collection<Models.Payroll>(); // GET: PayrollManagement public ActionResult Index() { return View(); } . . . No Change [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Models.Payroll payroll) { Payrolls.Add(payroll); return View(); } public ActionResult PaySummary() { return View(Payrolls); } } }
- Access the Create.cshtml document and add a link to the PaySummary view: @{ ViewBag.Title = "Create"; } <h2>Create</h2> <p>@Html.ActionLink("Payroll Summary", "PaySummary")</p>
- Access the PayrollStartUp.cshtml file and add a link to the PaySummary view in the bottom section of the document as follows: @{ ViewBag.Title = "Payroll Start-Up"; } <h2>Payroll Start-Up</h2> <hr /> @using (Html.BeginForm("PayrollPreparation", "PayrollManagement", FormMethod.Post)) { . . . No Change } <p>@Html.ActionLink("Payroll Summary", "PaySummary")</p>
- In the Solution Explorer, below Views, right-click PayrollManagement -> Add -> New Scaffolded Item...
- In the middle frame of the Add Scaffold dialog box, click MVC 5 View
- Click Add
- Type PaySummary as the name of the view
- Click Add
- Change the document as follows: @{ ViewBag.Title = "Pay Summary"; } <h2>Pay Symmary</h2> <table style="width: 500px;" border="5"> <tr> <td><b>Payroll #</b></td> <td><b>Employee #</b></td> <td><b>Net Pay</b></td> </tr> @foreach (var pay in Model) { <tr> <td>@pay.PayrollNumber</td> <td>@pay.EmployeeNumber</td> <td>@pay.NetPay</td> </tr> } </table> <p>@Html.ActionLink("Start a New Payroll", "PayrollStartUp")</p>
- To execute the project, on the main menu, click Debug -> Start Without Debugging:
- Click the Start a New Payroll link
- In the text boxes, type the following values: Employee #: 529485 Base Hourly Rate: 11.26 Base Tire Rate: 1.08 Monday: 118 Tuesday 46 Wednesday: 125 Thursday: 52 Friday: 97 Payroll #: 100001
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Payroll Summary button
- Click the Start a New Payroll link
- In the text boxes, type the following values: Employee #: 928547 Base Hourly Rate: 9.85 Base Tire Rate: 1.27 Monday: 88 Tuesday 96 Wednesday: 76 Thursday: 94 Friday: 62 Payroll #: 100002
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Payroll Summary button
- Click the Start a New Payroll link
- In the text boxes, type the following values: Employee #: 135170 Base Hourly Rate: 12.05 Base Tire Rate: 1.15 Monday: 64 Tuesday 102 Wednesday: 83 Thursday: 66 Friday: 88 Payroll #: 100003
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Payroll Summary Link:
- Close the browser and return to your programming environment
A Dynamic Model#
The WebViewPage.Model property is defined as follows:
public object Model { get; }This means that the WebViewPage.Model property is an anonymous object. It is also called a dynamic model. Normally, to access a model in a view, in the top section of the view, type @model. If you are using a dynamic model (as done above), follow @model with the dynamic keyword. As seen with other anonymous types (such as the ViewBag), the primary problem with the dynamic model is that it doesn't benefit from Intellisense. As a result, you must remember the names of the members you want to access. Practical Learning: Accessing a Dynamic Model
- Change the PaySummary.cshtml document as follows: @model dynamic @{ ViewBag.Title = "Pay Summary"; } <h2>Pay Symmary</h2> <table style="width: 500px;" border="5"> <tr> <td><b>Payroll #</b></td> <td><b>Employee #</b></td> <td><b>Base Hourly Rate</b></td> <td><b>Base Tire Rate</b></td> <td><b>Net Pay</b></td> </tr> @foreach(var pay in Model) { <tr> <td>@pay.PayrollNumber</td> <td>@pay.EmployeeNumber</td> <td>@pay.BaseHourlyRate</td> <td>@pay.BaseTireRate</td> <td>@pay.NetPay</td> </tr> } </table> <p>@Html.ActionLink("Start a New Payroll", "PayrollStartUp")</p>
- To execute the application, on the main menu, click Debug -> Start Without Debugging:
- Click the Start a New Payroll link
- In the text boxes, type the following values: Employee #: 294708 Base Hourly Rate: 10.88 Base Tire Rate: 1.08 Monday: 115 Tuesday 52 Wednesday: 128 Thursday: 46 Friday: 114 Payroll #: 100004
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Payroll Summary Link:
- Close the browser and return to your programming environment
The Role of a Creation Action#
In previous sections, we saw that a creation view, named Create and associated to an action of the same name, can be used to request values from a user, the values necessary to build an object. We also mentioned that such a view can be enough to handle the necessary object creation. We saw that there are situations where you need a separate view to take care of some other details. In this case, once the object has been created, you may need to display an appropriate view instead of the Create view. To do this, in the action method, you can call the RedirectToAction() method inherited by the controller class. Practical Learning: Using a Creation Action
- Access the PayrollManagementController.cs file and change the second Create() method as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TireDirect32.Controllers { public class PayrollManagementController : Controller { // This is a fixed list of employees used in this appl ication. // We are creating it here because we will not do any file processing in this project public Models.Employee[] Employees = new Models.Employee[] { new Models.Employee() { EmployeeNumber = 928547, FirstName = "Robert", LastName = "Simpson" }, new Models.Employee() { EmployeeNumber = 294708, FirstName = "Gabrielle", LastName = "Leighton" }, new Models.Employee() { EmployeeNumber = 529485, FirstName = "Peter", LastName = "Cotton" }, new Models.Employee() { EmployeeNumber = 135170, FirstName = "Jennifer", LastName = "Gallagher" } }; // This is a variable that will hold the list of payrolls for this project. // The "static" keyword is used so the records can be saved in memory while a user is creating records and using the website. // Such records will disappear once the session is over. public static Models.Collection<Models.Payroll> Payrolls = new Models.Collection<Models.Payroll>(); // GET: PayrollManagement public ActionResult Index() { return View(); } // GET: PayrollManagement/LoanContractStartUp public ActionResult PayrollStartUp() { return View(); } public ActionResult PayrollPreparation(FormCollection collection) { double payRate = 0.00; double tireRate = 0.00; double dailySalary = 0.00; long strEmployeeNumber = 0; double dInstallationMondayPay = 0.00; double dInstallationTuesdayPay = 0.00; double dInstallationWednesdayPay = 0.00; double dInstallationThursdayPay = 0.00; double dInstallationFridayPay = 0.00; if (!string.IsNullOrEmpty(collection["EmployeeNumber"])) { ViewBag.PayrollNumber = collection["PayrollNumber"]; try { ViewBag.EmployeeNumber = collection["EmployeeNumber"]; strEmployeeNumber = Convert.ToInt64(collection["EmployeeNumber"]); var staff = from empl in Employees where empl.EmployeeNumber == strEmployeeNumber select new { FirstName = empl.FirstName, LastName = empl.LastName, }; if (staff != null) { foreach (var clerk in staff) { ViewBag.FirstName = clerk.FirstName; ViewBag.LastName = clerk.LastName; } } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid employee number."; } try { if (!string.IsNullOrEmpty(collection["BaseHourlyRate"])) { ViewBag.BaseHourlyRate = collection["BaseHourlyRate"]; payRate = double.Parse(collection["BaseHourlyRate"]); dailySalary = payRate * 8.00; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid base hourly rate."; } try { if (!string.IsNullOrEmpty(collection["BaseTireRate"])) { ViewBag.BaseTireRate = collection["BaseTireRate"]; tireRate = double.Parse(collection["BaseTireRate"]); } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid rate (cost) for a tire installation."; } try { if (!string.IsNullOrEmpty(collection["MondayInstallations"])) { ViewBag.MondayInstallations = collection["MondayInstallations"]; dInstallationMondayPay = int.Parse(collection["MondayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Monday."; } try { if (!string.IsNullOrEmpty(collection["TuesdayInstallations"])) { ViewBag.TuesdayInstallations = collection["TuesdayInstallations"]; dInstallationTuesdayPay = int.Parse(collection["TuesdayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Tuesday."; } try { if (!string.IsNullOrEmpty(collection["WednesdayInstallations"])) { ViewBag.WednesdayInstallations = collection["WednesdayInstallations"]; dInstallationWednesdayPay = int.Parse(collection["WednesdayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Wednesday."; } try { if (!string.IsNullOrEmpty(collection["ThursdayInstallations"])) { ViewBag.ThursdayInstallations = collection["ThursdayInstallations"]; dInstallationThursdayPay = int.Parse(collection["ThursdayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Thursday."; } try { if (!string.IsNullOrEmpty(collection["FridayInstallations"])) { ViewBag.FridayInstallations = collection["FridayInstallations"]; dInstallationFridayPay = int.Parse(collection["FridayInstallations"]) * tireRate; } } catch (FormatException) { ViewBag.ErrorMessage = "You must provide a valid number for tires installed on Friday."; } double dMondayNetPay = dInstallationMondayPay; double dTuesdayNetPay = dInstallationTuesdayPay; double dWednesdayNetPay = dInstallationWednesdayPay; double dThursdayNetPay = dInstallationThursdayPay; double dFridayNetPay = dInstallationFridayPay; if (dInstallationMondayPay < dailySalary) { dMondayNetPay = dailySalary; } if (dInstallationTuesdayPay < dailySalary) { dTuesdayNetPay = dailySalary; } if (dInstallationWednesdayPay < dailySalary) { dWednesdayNetPay = dailySalary; } if (dInstallationThursdayPay < dailySalary) { dThursdayNetPay = dailySalary; } if (dInstallationFridayPay < dailySalary) { dFridayNetPay = dailySalary; } ViewBag.MondayNetPay = dMondayNetPay.ToString("F"); ViewBag.TuesdayNetPay = dTuesdayNetPay.ToString("F"); ViewBag.WednesdayNetPay = dWednesdayNetPay.ToString("F"); ViewBag.ThursdayNetPay = dThursdayNetPay.ToString("F"); ViewBag.FridayNetPay = dFridayNetPay.ToString("F"); ViewBag.NetPay = (dMondayNetPay + dTuesdayNetPay + dWednesdayNetPay + dThursdayNetPay + dFridayNetPay).ToString("F"); } return View(); } public ActionResult Create() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Models.Payroll payroll) { Payrolls.Add(payroll); return RedirectToAction ( "PayrollStartUp" ); } public ActionResult PaySummary() { return View(Payrolls); } } }
- Click the PayrollStartUp.cshtml tab to access it
- To execute the project, on the main menu, click Debug -> Start Without Debugging:
- In the text boxes, type the following values: Employee #: 294708 Base Hourly Rate: 12.25 Base Tire Rate: 1.35 Monday: 102 Tuesday 92 Wednesday: 74 Thursday: 66 Friday: 57 Payroll #: 100001
- Click the Prepare Payroll button
- Click the Save Payroll button
- In the text boxes, type the following values: Employee #: 135170 Base Hourly Rate: 12.05 Base Tire Rate: 1.15 Monday: 83 Tuesday 92 Wednesday: 88 Thursday: 96 Friday: 46 Payroll #: 100002
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Payroll Summary Link
- Close the browser and return to your programming environment
A Strongly-Typed Model#
A strongly-type model is a collection whose items are known to the Model object as opposed to a dynamic object. If you access a strongly-typed object in the code of your view, the Intellisence will assist you because it is aware of where the properties of the object are coming from. To indicate to the compiler that you want to use a strongly-typed model, in the top section of the code of the web page, follow @model by a class or interface that support the foreach loop. Normally, you should use IEnumerable<>, which is the interface explicitly made for the foreach loop. Practical Learning: Using a Strongly-Typed Model
- Access the PaySummary.cshtml file and change it as follows: @model IEnumerable<TireDirect3.Models.Payroll> @{ ViewBag.Title = "Pay Summary"; } <h2>Pay Symmary</h2> <table border="5"> <tr> <td><b>Payroll #</b></td> <td><b>Employee #</b></td> <td><b>Base Hourly Rate</b></td> <td><b>Base Tire Rate</b></td> <td><b>Monday Installations</b></td> <td><b>Monday Pay</b></td> <td><b>Tuesday Installations</b></td> <td><b>Tuesday Pay</b></td> <td><b>Wednesday Installations</b></td> <td><b>Wednesday Pay</b></td> <td><b>Thursday Installations</b></td> <td><b>Thursday Pay</b></td> <td><b>Friday Installations</b></td> <td><b>Friday Pay</b></td> <td><b>Net Pay</b></td> </tr> @foreach(var pay in Model) { <tr> <td>@pay.PayrollNumber</td> <td>@pay.EmployeeNumber</td> <td>@pay.BaseHourlyRate</td> <td>@pay.BaseTireRate</td> <td>@pay.MondayInstallations</td> <td>@pay.MondayPay</td> <td>@pay.TuesdayInstallations</td> <td>@pay.TuesdayPay</td> <td>@pay.WednesdayInstallations</td> <td>@pay.WednesdayPay</td> <td>@pay.ThursdayInstallations</td> <td>@pay.ThursdayPay</td> <td>@pay.FridayInstallations</td> <td>@pay.FridayPay</td> <td>@pay.NetPay</td> </tr> } </table> <p>@Html.ActionLink("Start a New Payroll", "PayrollStartUp")</p>
- Click the PayrollStartUp.cshtml tab to access it
- To execute the project, on the main menu, click Debug -> Start Without Debugging
- Click the Start a New Payroll link
- In the text boxes, type the following values: Employee #: 529485 Base Hourly Rate: 11.26 Base Tire Rate: 1.08 Monday: 118 Tuesday 46 Wednesday: 125 Thursday: 52 Friday: 97 Payroll #: 100001
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Start a New Payroll link
- In the text boxes, type the following values: Employee #: 928547 Base Hourly Rate: 9.85 Base Tire Rate: 1.27 Monday: 88 Tuesday 96 Wednesday: 76 Thursday: 94 Friday: 62 Payroll #: 100002
- Click the Prepare Payroll button
- Click the Save Payroll button
- In the text boxes, type the following values: Employee #: 135170 Base Hourly Rate: 12.05 Base Tire Rate: 1.15 Monday: 64 Tuesday 102 Wednesday: 83 Thursday: 66 Friday: 88 Payroll #: 100003
- Click the Prepare Payroll button
- Click the Save Payroll button
- In the text boxes, type the following values: Employee #: 294708 Base Hourly Rate: 11.75 Base Tire Rate: 1.42 Monday: 116 Tuesday 128 Wednesday: 93 Thursday: 121 Friday: 87 Payroll #: 100004
- Click the Prepare Payroll button
- Click the Save Payroll button
- Click the Payroll Summary Link:
- Close the browser and return to your programming environment
- In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
- In the Add Scaffold dialog box, click MVC 5 Controller - Empty and click Add
- Type PersonnelManagement to get PersonnelManagementController
- Click Add
- Change the document as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TireDirect33.Controllers { public class PersonnelManagementController : Controller { public static List<Models.Employee> Employees = new List<Models.Employee>(); // GET: PersonnelManagement public ActionResult Index() { return View(Employees); } // GET: PersonnelManagement/Create public ActionResult Create() { return View(); } // GET: PersonnelManagement/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection collection) { Models.Employee employee = new Models.Employee() { EmployeeNumber = long.Parse(collection["EmployeeNumber"]), FirstName = collection["FirstName"], LastName = collection["LastName"] }; Employees.Add(employee); return View(); } } }
- In the document, right-click inside the Index() and click Add View...
- In the dialog box, make sure the text box displays Index and click Add
- Change the document as follows: @model IEnumerable<TireDirect33.Models.Employee> @{ ViewBag.Title = "Employees Records"; } <h2>Employees Records</h2> <table style="width: 500px;" border="5"> <tr> <td><b>Employee #</b></td> <td><b>First Name</b></td> <td><b>Last Name</b></td> </tr> @foreach (var empl in Model) { <tr> <td>@empl.EmployeeNumber</td> <td>@empl.FirstName</td> <td>@empl.LastName</td> </tr> } </table> <p>@Html.ActionLink("Hire a New Employee", "Create")</p>
- In the Solution Explorer, under Views, right-click PersonnelManagement -> Add -> Controller...
- In the Add Scaffold dialog box, click MVC 5 View, and click Add
- Type Create as the name of the view
- Click Add
- Create a form as follows: @{ ViewBag.Title = "Employment Application"; } <h2>Employment Application</h2> @using (Html.BeginForm("Create", "PersonnelManagement", FormMethod.Post)) { <div class="form-group"> <label for="EmployeeNumber" class="col-md-2 control-label" style="width: 120px">Employee #:</label> <div class="col-md-10"> @Html.TextBox("EmployeeNumber", null, new { @class = "form-control", style = "width: 150px" }) </div> <label for="FirstName" class="col-md-2 control-label" style="width: 120px">First Name:</label> <div class="col-md-10"> @Html.TextBox("FirstName", null, new { @class = "form-control", style = "width: 150px" }) </div> <label for="LastName" class="col-md-2 control-label" style="width: 120px">Last Name:</label> <div class="col-md-10"> @Html.TextBox("LastName", null, new { @class = "form-control", style = "width: 150px" }) </div> </div> <p class="text-center" style="width: 400px"><input type="submit" name="btnSaveRecord" value="Hire Employee" /></p> } <p>@Html.ActionLink("Show Records", "Index")</p>
Primary Options on Creating A Model Class#
Binding the Properties to an Action#
As seen in previous sections, to access the controls of a form in a controller, you can add a FormCollection parameter to the method. In the body of the method, you can access the controls through the parameter as an indexed property. Here are examples:
public ActionResult Create(FormCollection collection)
{
Models.Employee employee = new Models.Employee()
{
EmployeeNumber = long.Parse(collection["EmployeeNumber"]),
FirstName = collection["FirstName"],
LastName = collection["LastName"]
};
Employees.Add(employee);
return View();
}Actually, in this case, FormCollection object is neither aware of, nor can it identity, the webcontrols of the form. This means that you must make sure the names by which you are accessing the controls are correct. Sometimes, by mistake, you may provide wrong values of controls. Here is an example:
public ActionResult Create(FormCollection collection)
{
Models.Employee employee = new Models.Employee()
{
EmployeeNumber = long.Parse(collection["EmployeeNumber"]),
FirstName = collection["First Name"],
LastName = collection["FamilyDesignation"]
};
Employees.Add(employee);
return View();
}The form associated with this action doesn't have a control named First Name nor a control named FamilyDesignation. When the form is used, it will not produce an error but of course the parts with the wrong names will not be recognized and if the object of the parameter class (the object of type Employee in this case) is asked to be saved, the parts with the wrong names will not be saved. To let you pass only the properties of the class to the method, ASP.NET MVC provides an attribute named Bind, from a class named BindAttribute. The BindAttribute class is defined in the System.Web.Mvc namespace and it is derived from the Attribute class. To use the Bind attribute, apply it to the parameter you are passing to the action method. The parameter must be of the model class. Here is an example
public ActionResult Create([Bind] Models.Employee staff)
{
return View();
}Normally, when you apply thi attribute, you shculd indicate the names of the properties that will be accessed through the parameter. To support this, the BindAttribute class is equipped with a property named Include which is a string:
public string Include { get; set; }When accessing this property, assign a string to it. In the string, create a list of the names of the controls that also correspond to the properties of the class model. Practical Learning: Binding Webcontrols to a Model
- Click the PersonnelManagementController.cs tab to access it and change the second Create() method follows: using System.Collections.Generic; using System.Web.Mvc; namespace TireDirect33.Controllers { public class PersonnelManagementController : Controller { public static List<Models.Employee> Employees = new List<Models.Employee>(); // GET: PersonnelManagement public ActionResult Index() { return View(Employees); } // GET: PersonnelManagement/Create public ActionResult Create() { return View(); } // GET: PersonnelManagement/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create( [Bind(Include = "EmployeeNumber, FirstName, LastName")] Models.Employee staff ) { Models.Employee employee = new Models.Employee() { EmployeeNumber = staff. EmployeeNumber, FirstName = staff. FirstName, LastName = staff. LastName }; Employees.Add(employee); return View(); } } }
Validating a Posted Model#
Remember that you usually create two Create() methods in your controller. The second Create() method actually creates a record using some values such as those from the webcontrols of a form in the corresponding view. The values that will be saved are actually stored in a dictionary-based collection named ModelStateDictionary. This collection holds what appears like a draft or a preview of the record that will be saved, but before the record is actually saved. As a normal dictionary-based class, a ModelStateDictionary object contains a list of property = value combinations of the values of the records that must be saved. Furthermore, the class allows you to check whether the record is ready to be saved or not. It does this through a read-only Boolean property named IsValid:
public bool IsValid { get; }When you check the value o this property, if it is true, it means the record is ready and will be saved, otherwise not. To let you access a ModelStateDictionary list of the record of an action method, the Controller class is equipped with a read-only property named ModelState that is of type ModelStateDictionary:
public ModelStateDictionary ModelState { get; }You can use this property to check the status of a record before taking an action on it. Practical Learning: Validating a Posted Model
- Change the method as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TireDirect33.Controllers { public class PersonnelManagementController : Controller { public static List<Models.Employee> Employees = new List<Models.Employee>(); // GET: PersonnelManagement public ActionResult Index() { return View(Employees); } // GET: PersonnelManagement/Create public ActionResult Create() { return View(); } // GET: PersonnelManagement/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Include = "EmployeeNumber, FirstName, LastName")] Models.Employee staff) { if(ModelState.IsValid) { Models.Employee employee = new Models.Employee() { EmployeeNumber = staff.EmployeeNumber, FirstName = staff.FirstName, LastName = staff.LastName }; Employees.Add(employee); return RedirectToAction("Index"); } return View(); } } }
- To execute the application, on the main menu, click Debug -> Start Without Debugging
- Close the browser and return to your programming environment
A Property as a Primary Key#
ASP.NET MVC gives you many options to control the behaviors of webcontrols. Most of the options are available in various classes of a namespace named System.ComponentModel.DataAnnotations. The System.ComponentModel.DataAnnotations namespace is defined in the System.ComponentModel.DataAnnotations.dll library. When you decide to use class a model for the records of a database, it very to indicate or know the property that is used as the primary key. To let you specify the primary key of a class, the System.ComponentModel.DataAnnotations namespace provides a class named KeyAttribute. This is an attribute you can apply to a property of your choice. As is the case for every attribute, to use the Key, type it before the access key of the property. Practical Learning: Creating a Primary Key in a Model
- In the Solution Explorer, under Models, double-click Employees.cs to access it
- Change the document as follows: using System.ComponentModel.DataAnnotations ; namespace TireDirect33.Models { public class Employee { [Key] public long EmployeeNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
- To preview the result, press Ctrl + F5
Saving Data#
ASP.NET MVC supports various means to create/generate, store, and manage data. One technique is serialization, which consists of saving an object, usually a list (a collection of objects). ASP.NET MVC doesn't specify when or how to save data. This is one of the decisions you will make based on your project. Practical Learning: Ending the Lesson
- Close your programming environment
Home Copyright © 2017-2019, C# Key Next

