An ASP.NET MVC Controller as a Class
An ASP.NET MVC Controller as a Class
A Folder for Controllers
The Controllers Folder
To manage the controllers of an ASP.NET MVC application, you create them in a special folder named Controllers.
Practical Learning: Introducing the Controllers Folder
Adding Types to the Controllers Folder
Controllers is primarily a folder like any other. This means that you can add any type of object, such as pictures, videos, in it. In the same way, you can create one or more classes, enumerations, structures, interfaces, etc, in that folder.
Practical Learning: Adding Types to the Controllers Folder
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CountriesStatistics01.Controllers { public enum Category { State, Province, Territory } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CountriesStatistics01.Controllers { interface IAbbreviated { string Abbreviation { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CountriesStatistics01.Controllers { interface IGovernmentEntity { string Name { get; set; } int Area { get; set; } string Capital { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CountriesStatistics01.Controllers { public struct Territory : IAbbreviated, IGovernmentEntity { // From the IAbbreviated interface public string Abbreviation { get; set; } // From the IGovernmentEntity interface public string Name { get; set; } public string Capital { get; set; } public int Area { get { return AreaLand + AreaWater; } set { } } // New Properties public int AreaLand { get; set; } public int AreaWater { get; set; } public Category TypeOfAdministration { get; set; } } }
Using Types from the Controllers Folder
If you create a non-static type (enumeration, structure, interface, class, etc) in the Controllers folder, to use an object of that type, you must declare a variable from it. You can then access the available members of that class.
Practical Learning: Using Types from the Controllers Folder
. . . No Change <hr /> @{ CountriesStatistics01.Controllers.Territory act = new CountriesStatistics01.Controllers.Territory(); act.Abbreviation = "ACT"; act.Name = "Australian Capital Territory"; act.AreaLand = 2280; act.AreaWater = 77; act.TypeOfAdministration = CountriesStatistics01.Controllers.Category.Territory; act.Capital = "Canberra"; } <table> <tr> <td style="width: 150px">Abbreviation:</td> <td>@act.Abbreviation</td> </tr> <tr> <td>Name:</td> <td>@act.Name</td> </tr> <tr> <td>Administration Type:</td> <td>@act.TypeOfAdministration</td> </tr> <tr> <td>Land Area:</td> <td>@act.AreaLand Km<sup>2</sup></td> </tr> <tr> <td>Water Area:</td> <td>@act.AreaWater Km<sup>2</sup></td> </tr> <tr> <td>Total Area:</td> <td>@act.Area Km<sup>2</sup></td> </tr> <tr> <td>Capital:</td> <td>@act.Capital,</td> </tr> </table> <hr /> <p><img src="~/Controllers/act.png" alt="Australian Capital Territory" width="938" height="469" /></p>
A Model Folder for Classes
Introduction to Models
One of the features of a website is that it allows visitors to interact with the webserver. Such a webserver may contain one or more databases. You on the other hand can create classes that communicate with a database. To support a common place where you can create and manage your classes, ASP.MVC provides a special folder named Models.
If you start an empty project in Microsoft Visual Studio, you can manually create a folder and name it Models. On the other hand, when starting a project, if you click either the MVC check box or the MVC icon, the studio would create the Models folder for you.
Practical Learning: Generating a Models Folder
Using the Models Folder
Once you have the Models folder, you can add a class to it. To do this, right-click the folder -> Add and choose the desired option such as New Item... or Class...
Practical Learning: Using the Models Folder
A Class Controller
Introduction
As seen in our introduction, a controller is created as a class. That class is primarily a regular class like any other. The class can contain any of the types of members we have seen so far (fields, properties, and methods). You can also create other types (structures, classes, interfaces, etc) in the same document.
Practical Learning: Introducing a Class Controller
using System; using System.Collections.Generic; using static System.Math; using System.Web; using System.Web.Mvc; namespace Geometry21.Controllers { public class GeometryController : Controller { // GET: Geometry public ActionResult Index() { return View(); } } public interface IPolyhedron { int Faces { get; set; } int Edges { get; set; } int Vertices { get; set; } double Edge { get; set; } double InscribedRadius { get; } double CircumscribedRadius { get; } double MidRadius { get; } double TotalArea { get; } double Volume { get; } } public class Octahedron : IPolyhedron { public int Faces { get; set; } public int Edges { get; set; } public int Vertices { get; set; } public double Edge { get; set; } public double InscribedRadius => Edge * Sqrt(6) / 6; public double CircumscribedRadius => Edge * Sqrt(2) / 2; public double MidRadius => Edge / 2; public double TotalArea => Edge * Edge * Sqrt(3) * 2; public double Volume => Edge * Edge * Edge * Sqrt(2) / 3; } }
using System; using System.Collections.Generic; using static System.Math; using System.Web; namespace Geometry21.Controllers { public class Tetrahedron : IPolyhedron { public int Faces { get; set; } public int Edges { get; set; } public int Vertices { get; set; } public double Edge { get; set; } public double FaceArea { get { return Edge * Edge * Sqrt(3) / 4; } } public double InscribedRadius => Edge / Sqrt(24); public double CircumscribedRadius => Edge * Sqrt(3 / 8); public double MidRadius => Edge / Sqrt(8); public double TotalArea => Edge * Edge * Sqrt(3); public double Volume => Edge * Edge * Edge / (6 * Sqrt(2)); public double IEdgescribedRadius => Edge / Sqrt(6); } }
A Variable of a Controller
Because a controller is primarily a class, you can declare a variable of it. The variable can be declared in a view associated with the controller or the variable can be declared and used in any file of the project. Here is an example of declaring a variable of a controller class:
@{
Geometry21.Controllers.GeometryController gc = null;
}
Of course, you must initialize the variable before using it. Here is an example:
@{
Exercises.Controllers.PolyhedronsController poly = new Exercises.Controllers.PolyhedronsController();
}
Remember that, to create a controller, you must derive a class from the Controller class. Controller is an abstract class. Based on this, if you want to access methods and properties defined in that class, you can use it when declaring a variable but you must initialize the variable using the class you created. Here is an example:
@{
Controller poly = new Exercises.Controllers.PolyhedronsController();
}
Of course, you can also declare the variable using var or the dynamic keyword. After declaring and initializing the variable using one of those techniques, you can use it any way you want. To access the members of the controller object, apply the period operator on the variable, followed by the desired member.
Practical Learning: Declaring a Variable of a Controller
. . . No Change <h2>Geometric Volumes: Octahedron</h2> @{ Geometry21.Controllers.PolyhedronsController poly = new Geometry21.Controllers.PolyhedronsController(); }
Fields in a Controller Class
As done in any class, you can declare any variable in a controller class. If the field is private, it can be accessed only inside the class. If you want a field to be accessible outside the class, make it public or internal.
If you create a field that is a class type, first, make sure you initialize it before using it. you can then access the members of the class from the field.
Practical Learning: Creating a Field in a Controller Class
using System;
using System.Collections.Generic;
using static System.Math;
using System.Web;
using System.Web.Mvc;
namespace Geometry21.Controllers
{
public class PolyhedronsController : Controller
{
public Octahedron Shape;
// GET: Polyhedrons
public ActionResult Index()
{
return View();
}
}
public interface IPolyhedron
{
. . . No Change
}
public class Octahedron : IPolyhedron
{
. . . No Change
}
}
Properties in a Controller Class
You can create properties in a controller class. Proceed as done for a normal class. After creating the property, you can access it from a variable of the class.
The Constructors of a Controller Class
You can create constructors in a controller class. You can create as many constructors as you want. As seen with the constructors of the classes we have created so far, a constructor is the favorite place to initialize the fields of a class.
A constructor is closely related to its view, and vice-versa. As a result, when a view-based webpage displays, the constructor(s) of its controller is(are) automatically called. This means that if you want an object to be used as soon as a webview displays, you can/should initialize it in a constructor of the controller.
Practical Learning: Adding a Constructor to a Controller
using System;
using System.Collections.Generic;
using static System.Math;
using System.Web;
using System.Web.Mvc;
namespace Geometry21.Controllers
{
public class PolyhedronsController : Controller
{
public Octahedron Shape;
public PolyhedronsController()
{
Shape = new Octahedron();
}
// GET: Polyhedrons
public ActionResult Index()
{
return View();
}
}
public interface IPolyhedron
{
int Faces { get; set; }
int Edges { get; set; }
int Vertices { get; set; }
double Edge { get; set; }
double InscribedRadius { get; }
double CircumscribedRadius { get; }
double MidRadius { get; }
double TotalArea { get; }
double Volume { get; }
}
public class Octahedron : IPolyhedron
{
public int Faces { get; set; }
public int Edges { get; set; }
public int Vertices { get; set; }
public double Edge { get; set; }
public double InscribedRadius => Edge * Sqrt(6) / 6;
public double CircumscribedRadius => Edge * Sqrt(2) / 2;
public double MidRadius => Edge / 2;
public double TotalArea => Edge * Edge * Sqrt(3) * 2;
public double Volume => Edge * Edge * Edge * Sqrt(2) / 3;
}
}
. . . No Change <h2>Geometric Volumes: Octahedron</h2> @{ Geometry21.Controllers.PolyhedronsController poly = new Geometry21.Controllers.PolyhedronsController(); if (IsPost) { poly.Shape.Edge = Convert.ToDouble(Request["txtEdge"]); } } @using (Html.BeginForm()) { <table> <tr> <td style="width: 395px" rowspan="9"> <img src="~/Images/polyhedron.png" width="460" height="456" alt="Geometric Volumes - Octahedron"> </td> <td class="caption">Edge:</td> <td>@Html.TextBox("txtEdge", @poly.Shape.Edge, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td> </td> <td style="text-align: center"><input type="submit" name="btnSubmit" value="Calculate" class="btn btn-default" /></td> </tr> <tr> <td>Number of Faces:</td> <td>@Html.TextBox("txtNumberOfFaces", @poly.Shape.Faces, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td>Number of Edges:</td> <td>@Html.TextBox("txt>NumberOfEdges", @poly.Shape.Edges, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td>Number of Vertices:</td> <td>@Html.TextBox("txtNumberOfVertices", @poly.Shape.Vertices, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td>Inscribed Radius:</td> <td>@Html.TextBox("txtInscribedRadius", @poly.Shape.InscribedRadius, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td>Circumscribed Radius:</td> <td>@Html.TextBox("txtCircumscribedRadius", @poly.Shape.CircumscribedRadius, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td>Total Area:</td> <td>@Html.TextBox("txtTotalArea", @poly.Shape.TotalArea, htmlAttributes : new { @class="form-control" })</td> </tr> <tr> <td>Volume:</td> <td>@Html.TextBox("txtVolume", @poly.Shape.Volume, htmlAttributes : new { @class="form-control" })</td> </tr> </table> }
Methods in a Controller Class
You can create methods in a controller class. If the method is not static, you can call it from a variable of the class. Everything is done as for the other methods we have created so far in classes.
Parameters in Members of a Controller
Constructors and methods can use parameters. The advantage of a constructor is that it is a good place to directly provide a value to a view.
Introduction to Forms in a Controller/View Architecture
A View and its Controlling Action
Remember that you must have an action/method in a controller before creating a view, and both must have the same name. When a view displays or is refreshed in a browser, its action immediately runs or executes. As a result, if you want to do something early on a webpage, you can put it in the action, of course before the return line. The method/action of a view executes only once, when the webpage displays for the first time or is refreshed. If you want its action to execute again, you must find some way to make it happen.
Practical Learning: Introducing Controllers
namespace PayrollPreparation12.Controllers
{
public class WorkDay
{
public WorkDay(double time, double salary)
{
HourSalary = salary;
TimeWorked = time;
}
public double HourSalary { get; set; }
public double TimeWorked { get; set; }
public double OvertimeRate => HourSalary * 1.50;
public double RegularTime
{
get
{
if (TimeWorked <= 8.00)
return TimeWorked;
else
return 8.00;
}
}
public double Overtime
{
get
{
if (TimeWorked <= 8.00)
return 0.00;
else
return TimeWorked - 8.00;
}
}
public double RegularPay => RegularTime * HourSalary;
public double OvertimePay => OvertimeRate * Overtime;
public double NetPay => RegularPay + OvertimePay;
}
}
The Controller of a Form
When processing a form, you can write all of the code you need in the webpage as we have done so far. In other cases, some of the processing can be done in the controller class. In this case, when creating the form, you can specify in what controller class the processing will be done.
The Action that Processes a Form
So far in our previous lessons, to perform the operations of a form, we wrote our code in an if(IsPost){} section in a webpage. As an alternative, for one reason or another, you may prefer to process a form in a controller class. To support this, the BeginForm() method provides a version whose syntax is:
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName);
This version takes two arguments. The second argument is the name of the controller that contains the code that processes the form. The first argument is a string that is the name of the method that processes the form. Normally, this method is an action. Therefore, the method should return an ActionResult-type of object.
Practical Learning: Creating a Form
using System.Web.Mvc;
namespace PayrollPreparation12.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
. . . No Change
public ActionResult PayrollPreparation()
{
return View();
}
}
}
. . . No Change
<h2>Payroll Preparation</h2>
@using (Html.BeginForm())
{
}
Returning a Parameterized View
As seen so far, to specify the action that manages a view, you can (this is not a requirement) create a method that returns an ActionResult type of object. To simplify this job, the Controller class is equipped with an overloaded method named View. As a matter of fact, the Controller.View() method provides various versions for different reasons. One of the versions of this method uses the following syntax:
protected internal ViewResult View(string viewName);
This version takes the name of a view as argument.
Practical Learning: Returning a Parameterized View
using System.Web.Mvc;
namespace PayrollPreparation12.Controllers
{
public class HomeController : Controller
{
. . . No Change
public ActionResult PayrollPreparation()
{
return View();
}
public ActionResult PayrollSummary()
{
return View("PayrollPreparation");
}
}
}
. . . No Change
<h2>Payroll Preparation</h2>
@using (Html.BeginForm("PayrollSummary", "Home"))
{
}
A Parameterized Action
An action is primarily a function like any other. It can use one or more arguments. A parameter can be any type of your choice, and you can pass as many parameters as you want. Here are different examples of actions that use parameters:
using System.Web.Mvc; namespace Exercises.Controllers { public class ExerciseController : Controller { public ActionResult Index() { return View(); } public ActionResult NewItem() { return View(); } public ActionResult Doubler(double number) { return View(); } public ActionResult Addition(object value, object valeur) { return View(); } public ActionResult Summary(string str, object report, int number, bool never) { return View(); } } }
In the body of the method, you can use or ignore one, some, or all of the argument(s).
Practical Learning: Creating a Parameterized Action
using System.Web.Mvc;
namespace PayrollPreparation12.Controllers
{
public class HomeController : Controller
{
. . . No Change
public ActionResult PayrollPreparation()
{
return View();
}
public ActionResult PayrollSummary(string HourlySalary,
string Monday, string Tuesday, string Wednesday,
string Thursday, string Friday)
{
return View("PayrollPreparation");
}
}
}
The Transmitting Method of a Form
The method of a form determines how the values would be transmitted by the protocol used. The two primary options are POST and GET. If you don't specify the method, it is assumed to be POST. To allow you to specify the method of transmission, the Html.BeginForm() method is available in the following version:
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method;)
The method is specified through an enumeration named FormMethod. Its two self-explanatory members are Get and Post.
Practical Learning: Specifying the Method of a Form
. . . No Change
<h2>Payroll Preparation</h2>
@using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post))
{
}
The HTML Attributes of a Form
In HTML, a form is created with a tag and, like most tags in HTML, a form has many attributes that allow you to set many of its options. In HTML, every attribute has a name and may have a value. For example, the name of an HMTL form is one of its attributes. To let you specify the attributes of a form, the Html.BeginForm() method is available in the following version:
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes);
The attributes are provides inside the curly brackets of new { }. Each attribute is provided as name=value where name is the name of the attribute recognized in HTML. The value is provided as a string, usually in double-quotes. The attributes are separated by commas.
Practical Learning: Specifying the Name of a Form
. . . No Change
<h2>Payroll Preparation</h2>
@using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post, new { name="frmPayroll" }))
{
}
|
||
Previous | Copyright © 2017-2021, FunctionX | Next |
|