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 LearningPractical Learning: Introducing the Controllers Folder

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected in the middle list.
    Change the Name of the project as CountriesStatistics01
  4. Click OK
  5. In the Templates list of the New ASP.NET Web Application, click the MVC icon and click OK
  6. In the Solution Explorer, right-click CountriesStatistics01 -> Add -> New Folder
  7. Type Images

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 LearningPractical Learning: Adding Types to the Controllers Folder

  1. In the Solution Explorer, right-click the Controllers folder -> Add -> New Item...
  2. In the left frame of the Add New Item dialog box, click Visual C# and, in the middle frame, make sure Class is selected
  3. Change the Name to Category
  4. Click Add
  5. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace CountriesStatistics01.Controllers
    {
        public enum Category
        {
            State,
            Province,
            Territory
        }
    }
  6. In the Solution Explorer, right-click the Controllers folder -> Add -> New Item...
  7. In the left frame of the Add New Item dialog box, click Code

  8. In the middle list, click Interface
  9. Change the name to Abbreviated
  10. Press Enter
  11. Change the HTML code as follows:
    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; }
        }
    }
    
  12. In the Solution Explorer, right-click Controllers -> Add -> Interface (if you don't see Interface, click New Item... and click Interface in the dialog box)
  13. In the middle frame, make sure Interface is selected and change the Name to GovernmentEntity
  14. Click OK
  15. Create the class as follows:
    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; }
        }
    }
  16. In the Solution Explorer, right-click Controllers -> Add -> Class
  17. Type Territory as the Name of the class
  18. Click Add
  19. Change the class as follows:
    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; }
        }
    }
  20. Save the following picture to your computer:

    Australian Capital Territory

  21. Right-click the picture where you save it, click Copy, and return to your programming environment
  22. In the Solution Explorer, right-click the Images folder and click Paste

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 LearningPractical Learning: Using Types from the Controllers Folder

  1. In the Solution Explorer, expand Views and expand Home
  2. Double-click About.cshtml to open it

  3. Change the document as follows:
    . . . 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>
  4. To execute the project, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging

    Accessing the Members of an Array

  5. Close the browser and return to your programming environment
  6. To start a new website, on the main menu of Microsoft Visual Studio, click File -> New -> Project ...
  7. In the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected.
    Change the Name to Geometry21
  8. Press Enter
  9. In the New ASP.NET Web Application, in the Templates list, make sure the MVC icon is selected and click OK
  10. Save the following picture to your computer:

    Polyhedron

  11. In the Solution Explorer, right-click Geometry21 -> Add -> New Floder
  12. Type Images
  13. Add the above picture to the Images folder
  14. To save everything, on the Standard toolbar, click the Save All button Save All

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 LearningPractical Learning: Generating a Models Folder

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle frame of the New Project dialog box, click ASP.NET Web Application (.NET Framework) and change the project Name to DepartmentStore08
  3. In the middle frame of the New ASP.NET Web Application dialog box, click Empty and, in the Add Folders and Core References For section, click the MVC check box:

    New Project

  4. Click OK

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 LearningPractical Learning: Using the Models Folder

  1. In the Solutions Explorer, right-click Models -> Add -> Class...
  2. Type StoreItem
  3. Click Add
  4. To save everything, on the Standard toolbar, click the Save All button
  5. On the main menu, click File -> Recent Projects and Solutions -> Geometry21

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 LearningPractical Learning: Introducing a Class Controller

  1. In the Solution Explorer, right-click the Controllers folder -> Add -> New Scaffolded Item...
  2. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller - Empty
  3. Click Add
  4. Type Polyhedrons to get PolyhedronsController
  5. Click Add
  6. Change the document as follows:
    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;
        }
    }
  7. In the Solution Explorer, right-click the Controllers folder -> Add -> Class...
  8. Type Tetrahedron as the Name of the file
  9. Click Add
  10. Complete the class as follows:
    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 LearningPractical Learning: Declaring a Variable of a Controller

  1. In the Solution Explorer, under Views, right-click Polyhedrons -> Add -> New Scaffolded Item...
  2. In the Add Scaffold dialog dialog box, click MVC 5 View
  3. Click Add
  4. Type Index as the View Name
  5. Click Add
  6. Change the document as follows:
    . . . 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 LearningPractical Learning: Creating a Field in a Controller Class

  1. In the Solution Explorer, under Controllers, double-click PolyhedronsController.cs to access it
  2. Create a field as follows:
    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 LearningPractical Learning: Adding a Constructor to a Controller

  1. Change the class as follows:
    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;
        }
    }
  2. In the Solution Explorer, under Views and under Polyhedrons, double-click Index.cshtml to access it
  3. Change the document as follows:
    . . . 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>&nbsp;</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>
    }
  4. To execute the application to test the form, on the main menu, click Debug -> Start Without Debugging:

    Introducing Interfaces

  5. In the Edge text box, type a number such as 138.73
  6. Click the Calculate button:

    Creating and Using Virtual Members

  7. Close the browser and return to your programming environment

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 LearningPractical Learning: Introducing Controllers

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the central list, click ASP.NET Web Application (.NET Framework) and change the project Name to PayrollPreparation12
  3. Click OK
  4. In the New ASP.NET Web Application, make sure the MVC icon is selected and click OK
  5. In the Solution Explorer, right-click Controllers -> Add -> Class...
  6. Type WorkDay as the Name of the file
  7. Click Add
  8. Change the class as follows:
    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 LearningPractical Learning: Creating a Form

  1. In the Solution Explorer, under Controllers, double-click HomeController.cs to open it
  2. Change the class as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation12.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            . . . No Change
    
            public ActionResult PayrollPreparation()
            {
                return View();
            }
        }
    }
  3. In the Solution Explorer, expand Views, right-click Home -> Add -> New Scaffolded Item...
  4. In the middle list of the Add Scaffold dialog box, click MVC 5 View
  5. Click Add
  6. Type PayrollPreparation as the View Name
  7. Click Add
  8. Change the document as follows:
    . . . 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 LearningPractical Learning: Returning a Parameterized View

  1. Access the HomeController.cs file and change the class as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation12.Controllers
    {
        public class HomeController : Controller
        {
    
            . . . No Change
    
            public ActionResult PayrollPreparation()
            {
                return View();
            }
    
            public ActionResult PayrollSummary()
            {
                return View("PayrollPreparation");
            }
        }
    }
  2. Access the PayrollPreparation.cshtml file and change it as follows:
    	. . . 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 LearningPractical Learning: Creating a Parameterized Action

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 LearningPractical Learning: Specifying the Method of a Form

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 LearningPractical Learning: Specifying the Name of a Form

  1. Change the PayrollPreparation.cshtml file as follows:
    . . . No Change
    
    <h2>Payroll Preparation</h2>
    
    @using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post, new { name="frmPayroll" }))
    {
    
    }
  2. Save everything
  3. Close your programming environment

Previous Copyright © 2017-2021, FunctionX Next