A View Bag in a Controller

Introduction

It is important to be able to send values or objects (data) from a controller to (one of) its webpage(s). ASP.NET MVC makes this operation very easy. To allow you to exchange data from a controller to a webpage, the ControllerBase class (the parent of the Controller class) is equipped with a property named ViewBag:

public object ViewBag { get; }

ViewBag is an anonymous object, actually a dynamic type of object. This means that it can be anything.

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 PayrollPreparation13
  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 PayrollPreparation13.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;
        }
    }
  9. In the Solution Explorer, under Controllers, double-click HomeController.cs to open it
  10. Change the class as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation13.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            . . . 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");
            }
        }
    }
  11. In the Solution Explorer, expand Views, right-click Home -> Add -> New Scaffolded Item...
  12. In the middle list of the Add Scaffold dialog box, click MVC 5 View
  13. Click Add
  14. Type PayrollPreparation as the View Name
  15. Click Add
  16. Change the document as follows:
    . . . No Change
    
    <h2>Payroll Preparation</h2>
    
    @using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post, new { name="frmPayroll" }))
    {
    
    }

Adding a Property to a View Bag in a Controller

To create a value to send to a view, in the method (the action) of a webpage in the controller class, type ViewBag, add a period to it, and add any name of a property you want. You can (must) then assign a value (any value you want) to that property. Here is an example:

using System.Web.Mvc;

namespace PayrollPreparation.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.MonthlySalary = 1580.75;
            
            return View();
        }
    }
}

In the same way, you can add various properties to the ViewBag object and assign different values to them. If you want to involve the values in numeric expressions, you may have to convert them first.

A Primary Message for a View

Remember that when a view (a webpage) displays, its action/method first runs. When you create an ASP.NET MVC project in Microsoft Visual Studio, the studio adds a property named Message to a ViewBag object and assigns a string to it. The string is then accessed from the view of the action.

A View Bag in a View

Introduction

The ViewResultBase class, the parent of webpages, is equipped with a property named ViewBag that its child classes inherit:

public object ViewBag { get; }

The ViewBag object of a webpage works in one of two ways. It can be used to get values from a controller or it can work with a layout page.

Data Exchange from a View to a Controller

If you add a property to a ViewBag in a controller and assign a value to that property, you can get that value from the view (the webpage) associated with the method. If you apply the same property name you had created in the controller, the view bag of the view automatically receives the value that was assigned in the controller. Based on this, to get the value that was assigned to a view bag property, in the view where you want the value, type ViewBag, followed by a period and the name of the property you had created in the controller.

Viewing a Bag in an Action

One of the advantages of an anonymous type such as ViewBag is that it allows you to return any type of value from a method. To do this, after a ViewResultBase object, a period, and ViewBag., type any name of property of your choice. You can then return such a value from a method. Here is an example:

using System.Web.Mvc;

namespace Exercises.App_Code
{
    public class CustomerInvoice : BillPreparation
    {
        public ViewResult Create()
        {
            ViewResult vr = new ViewResult();

            return vr;
        }

        public string Present(ViewResult vr)
        {
            return vr.ViewBag.SubTitle;
        }
    }
}

Laying Out a View Bag

As you know already, the layout page is the central document of a website as far view display is concerned. Based on this, ASP.NET MVC makes it possible to create a value for each webpage . Then indicate to the layout where to display the value for each webpage but the value to display will depend on the webâge.

To create a value that the layout page would conditionally dispending on the webpage, in an @{} section of every desired webpage, add a property to a ViewBag object. Assign the desired value to it. Apply the exact same property to every page you want but assign a different value.

To access the common property, in the layout document, type @ViewBag, a period, and the common name of the property you had created. Alaos, in the layout page, make sure you select the appropriate section because the property would always display in that section.

The Conditional Titles of Web Pages

As you may know already, every webpage has a title. The title displays in the <head></head> section of the HTML code. ASP.NET MVC allows you to create a title for each webpage and pass them to the layout page. The layout page would display the title depending on the webpage that is being displayed.

To create the titles of the webpages, in every webpage, create an @{} section. In the square brackets, type ViewBag.Title and assign the desired value, usually a string, to it. To display the titles, in the layout document, inside the <title></title> section, type @ViewBag.Title.

Practical LearningPractical Learning: Specifying the Title of a Web Page

A View Bag for a Form

Preparing Values for a Form

One of the ways you will use the ViewBag object is to exchange values between an action method of a controller and its associated view. Normally, the values are primarily passed as parameters to the action in the controller. Here is an example we saw:

using System.Web.Mvc;

namespace Exercises.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult PayrollSummary(string strGrossSalary, string State)
        {
            return View("PayrollPreparation");
        }
    }
}

In the body of the method, do what you want. Other than that, access a ViewBag object. Add one or more properties. Assign the desired value to each property. You can assign a constant value, the name of a variable, or an expression.

Practical LearningPractical Learning: Preparing Values for a Form

Accessing the Values from an Action

To get a form that smoothly communicates with a controller, there are some steps you should follow. When creating the form, for each control whose value will be processed in the method, give the name of the parameter that will be passed to the method. To put it another way, when creating the method in the controller, give it the name used as the first argument of the Html.BeginForm() method.

In the form, if you want a control to display a value from the controller, give its name as a property that was applied to a ViewBag object in the method. To put it another way, in the action method, create a ViewBag property for each control that will display a value in the form and use the name of the ontrol as the name of the view bag property.

Practical LearningPractical Learning: Accessing the Values from an Action

  1. Access the PayrollPreparation.cshtml file and change it as follows:
    @{
        ViewBag.Title = "Payroll Preparation";
    }
    
    <h2>Payroll Preparation</h2>
    
    @using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post, new { name = "frmPayroll" }))
    {
        <table>
            <tr>
                <td style="width: 110px"><b>Hourly Salary:</b></td>
                <td colspan="5">@Html.TextBox("HourlySalary")</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><b>Monday</b></td>
                <td><b>Tuesday</b></td>
                <td><b>Wednesday</b></td>
                <td><b>Thursday</b></td>
                <td><b>Friday</b></td>
            </tr>
            <tr>
                <td><b>Time Workd:</b></td>
                <td>@Html.TextBox("Monday")</td>
                <td>@Html.TextBox("Tuesday")</td>
                <td>@Html.TextBox("Wednesday")</td>
                <td>@Html.TextBox("Thursday")</td>
                <td>@Html.TextBox("Friday")</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="5" style="text-align: center; height: 32px;">
                     <input type="submit" name="btnCalculate" style="width: 400px" value="Calculate" /></td>
            </tr>
            <tr>
                <td><b>Regular Time:</b></td>
                <td>@Html.TextBox("MondayRegularTime")</td>
                <td>@Html.TextBox("TuesdayRegularTime")</td>
                <td>@Html.TextBox("WednesdayRegularTime")</td>
                <td>@Html.TextBox("ThursdayRegularTime")</td>
                <td>@Html.TextBox("FridayRegularTime")</td>
            </tr>
            <tr>
                <td><b>Overtime:</b></td>
                <td>@Html.TextBox("MondayOvertime")</td>
                <td>@Html.TextBox("TuesdayOvertime")</td>
                <td>@Html.TextBox("WednesdayOvertime")</td>
                <td>@Html.TextBox("ThursdayOvertime")</td>
                <td>@Html.TextBox("FridayOvertime")</td>
            </tr>
            <tr>
                <td><b>Regular Pay:</b></td>
                <td>@Html.TextBox("MondayRegularPay")</td>
                <td>@Html.TextBox("TuesdayRegularPay")</td>
                <td>@Html.TextBox("WednesdayRegularPay")</td>
                <td>@Html.TextBox("ThursdayRegularPay")</td>
                <td>@Html.TextBox("FridayRegularPay")</td>
            </tr>
            <tr>
                <td><b>Overtime Pay:</b></td>
                <td>@Html.TextBox("MondayOvertimePay")</td>
                <td>@Html.TextBox("TuesdayOvertimePay")</td>
                <td>@Html.TextBox("WednesdayOvertimePay")</td>
                <td>@Html.TextBox("ThursdayOvertimePay")</td>
                <td>@Html.TextBox("FridayOvertimePay")</td>
            </tr>
        </table>
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Accessing the Values from an Action

  3. In the top text box, enter some values as follows:
    Hourly Salary: 26.68
    Monday:         8
    Tuesday:       10.5
    Wednesday:      6.5
    Thursday:       9.5
    Friday:         7

    Accessing the Values from an Action

  4. Click the button:

    Accessing the Values from an Action

  5. Close the browser and return to your programming environment

A View Bag Property as a String

As another technique you can use to retrieve the value of a property applied to a view bag, after creating the view vag in a controller, as the argument of the intended control, use the following formula

ViewBag.property-name as string

Data Exchange Between Two Views

It is traditionally somewhat difficult to transfer values from one webpage to another. To take care of this in ASP.NET MVC, you can use a type of triangular relationship. You can create two actions as mentioned in the previous section. Create a view that will receive the values. In the action that is passed as argument to the form, pass the name of the second action to the View() call.

Practical LearningPractical Learning: Setting the Width of a Form

  1. Access the HomeController.cs file and change it as follows::
    using System;
    using System.Web.Mvc;
    
    namespace PayrollPreparation13.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = &quot;Your application description page.&quot;;
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = &quot;Your contact page.&quot;;
    
                return View();
            }
    
            public ActionResult TimeSheet()
            {
                return View();
            }
    
            public ActionResult PayrollPreparation(string HourlySalary,
                                               string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
            {
                double hSalary = Convert.ToDouble(HourlySalary);
                double mon = Convert.ToDouble(Monday);
                double tue = Convert.ToDouble(Tuesday);
                double wed = Convert.ToDouble(Wednesday);
                double thu = Convert.ToDouble(Thursday);
                double fri = Convert.ToDouble(Friday);
    
                WorkDay wdMonday = new WorkDay(mon, hSalary);
                WorkDay wdTuesday = new WorkDay(tue, hSalary);
                WorkDay wdWednesday = new WorkDay(wed, hSalary);
                WorkDay wdThursday = new WorkDay(thu, hSalary);
                WorkDay wdFriday = new WorkDay(fri, hSalary);
    
                ViewBag.MondayRegularTime = wdMonday.RegularTime.ToString(&quot;F&quot;);
                ViewBag.MondayOvertime = wdMonday.Overtime.ToString(&quot;F&quot;);
                ViewBag.MondayRegularPay = wdMonday.RegularPay.ToString(&quot;F&quot;);
                ViewBag.MondayOvertimePay = wdMonday.OvertimePay.ToString(&quot;F&quot;);
    
                ViewBag.TuesdayRegularTime = wdTuesday.RegularTime.ToString(&quot;F&quot;);
                ViewBag.TuesdayOvertime = wdTuesday.Overtime.ToString(&quot;F&quot;);
                ViewBag.TuesdayRegularPay = wdTuesday.RegularPay.ToString(&quot;F&quot;);
                ViewBag.TuesdayOvertimePay = wdTuesday.OvertimePay.ToString(&quot;F&quot;);
    
                ViewBag.WednesdayRegularTime = wdWednesday.RegularTime.ToString(&quot;F&quot;);
                ViewBag.WednesdayOvertime = wdWednesday.Overtime.ToString(&quot;F&quot;);
                ViewBag.WednesdayRegularPay = wdWednesday.RegularPay.ToString(&quot;F&quot;);
                ViewBag.WednesdayOvertimePay = wdWednesday.OvertimePay.ToString(&quot;F&quot;);
    
                ViewBag.ThursdayRegularTime = wdThursday.RegularTime.ToString(&quot;F&quot;);
                ViewBag.ThursdayOvertime = wdThursday.Overtime.ToString(&quot;F&quot;);
                ViewBag.ThursdayRegularPay = wdThursday.RegularPay.ToString(&quot;F&quot;);
                ViewBag.ThursdayOvertimePay = wdThursday.OvertimePay.ToString(&quot;F&quot;);
    
                ViewBag.FridayRegularTime = wdFriday.RegularTime.ToString(&quot;F&quot;);
                ViewBag.FridayOvertime = wdFriday.Overtime.ToString(&quot;F&quot;);
                ViewBag.FridayRegularPay = wdFriday.RegularPay.ToString(&quot;F&quot;);
                ViewBag.FridayOvertimePay = wdFriday.OvertimePay.ToString(&quot;F&quot;);
    
                return View();
            }
        }
    }
  2. In the Solution Explorer, under Views, right-click Home -> Add -> View...
  3. Type TimeSheet as the name of the view
  4. Click Add
  5. Change the document as follows:
    @{
        ViewBag.Title = "Employee Time Sheet";
    }
    
    <h2>Employee Time Sheet</h2>
    
    @using (Html.BeginForm("PayrollPreparation", "Home", FormMethod.Post, new { name = "frmPayroll" }))
    {
        <table>
            <tr>
                <td style="width: 110px"><b>Hourly Salary:</b></td>
                <td>@Html.TextBox("HourlySalary", "0.00", new { style = "width: 80px" })</td>
            </tr>
        </table>
        <hr />
        <table>
            <tr>
                <td style="width: 110px">&nbsp;</td>
                <td><b>Monday</b></td>
                <td><b>Tuesday</b></td>
                <td><b>Wednesday</b></td>
                <td><b>Thursday</b></td>
                <td><b>Friday</b></td>
            </tr>
            <tr>
                <td><b>Time Workd:</b></td>
                <td>@Html.TextBox("Monday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Tuesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Wednesday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Thursday", "0.00", new { style = "width: 80px" })</td>
                <td>@Html.TextBox("Friday", "0.00", new { style = "width: 80px" })</td>
            </tr>
        </table>
        <hr />
        <table>
            <tr>
                <td style="width: 110px">&nbsp;</td>
                <td><input type="submit" name="btnPrepararePayroll" style="width: 400px" value="Preparare Payroll" /></td>
            </tr>
        </table>
    }
  6. Access the PayrollPreparation.cshtml file and change it as follows:
    @{
        ViewBag.Title = "Payroll Preparation";
    }
    
    <h2>Payroll Preparation</h2>
    
    @using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post, new { name = "frmPayroll" }))
    {
        <table>
            <tr>
                <td style="width: 110px"><b>Hourly Salary:</b></td>
                <td colspan="5">@Html.TextBox("HourlySalary")</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><b>Monday</b></td>
                <td><b>Tuesday</b></td>
                <td><b>Wednesday</b></td>
                <td><b>Thursday</b></td>
                <td><b>Friday</b></td>
            </tr>
            <tr>
                <td><b>Time Workd:</b></td>
                <td>@Html.TextBox("Monday")</td>
                <td>@Html.TextBox("Tuesday")</td>
                <td>@Html.TextBox("Wednesday")</td>
                <td>@Html.TextBox("Thursday")</td>
                <td>@Html.TextBox("Friday")</td>
            </tr>
            <tr>
                <td><b>Regular Time:</b></td>
                <td>@Html.TextBox("MondayRegularTime")</td>
                <td>@Html.TextBox("TuesdayRegularTime")</td>
                <td>@Html.TextBox("WednesdayRegularTime")</td>
                <td>@Html.TextBox("ThursdayRegularTime")</td>
                <td>@Html.TextBox("FridayRegularTime")</td>
            </tr>
            <tr>
                <td><b>Overtime:</b></td>
                <td>@Html.TextBox("MondayOvertime")</td>
                <td>@Html.TextBox("TuesdayOvertime")</td>
                <td>@Html.TextBox("WednesdayOvertime")</td>
                <td>@Html.TextBox("ThursdayOvertime")</td>
                <td>@Html.TextBox("FridayOvertime")</td>
            </tr>
            <tr>
                <td><b>Regular Pay:</b></td>
                <td>@Html.TextBox("MondayRegularPay")</td>
                <td>@Html.TextBox("TuesdayRegularPay")</td>
                <td>@Html.TextBox("WednesdayRegularPay")</td>
                <td>@Html.TextBox("ThursdayRegularPay")</td>
                <td>@Html.TextBox("FridayRegularPay")</td>
            </tr>
            <tr>
                <td><b>Overtime Pay:</b></td>
                <td>@Html.TextBox("MondayOvertimePay")</td>
                <td>@Html.TextBox("TuesdayOvertimePay")</td>
                <td>@Html.TextBox("WednesdayOvertimePay")</td>
                <td>@Html.TextBox("ThursdayOvertimePay")</td>
                <td>@Html.TextBox("FridayOvertimePay")</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="5" style="text-align: center; height: 32px;"><input type="submit" name="btnCalculate" style="width: 400px" value="Calculate" /></td>
            </tr>
        </table>
    }
  7. Access the TimeSheet.cshtml file
  8. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Accessing the Values from an Action

  9. In the top text box, enter some values as follows:
    Hourly Salary: 16.57
    Monday:         7.5
    Tuesday:       12
    Wednesday:      9.5
    Thursday:       8
    Friday:         6.5

    Accessing the Values from an Action

  10. Click the button:

    Accessing the Values from an Action

  11. Close the browser and return to your programming environment

Viewing a Bag in an HTML Helper

The HtmlHelper class is directly derived from Object but it is equipped with the ViewBag property, like the one we reviewed for the WebPage class.

Web Page and Web View Redirection

Introduction

Redirection consists of automatically send a visitor to a certain webpage for any reason you judge necessary. For example, you might created a webpage. You find out or decide that the webpage is not necessary anymore but for some reason, you don't to delete it (one reason could be that many people use the address of that webpage to locate it; if you delete the webpage, its related links would be broken). Another reason could be that you create a webpage or view that is used only as a transitional step to relate two other webpages or views.

Both the IIS webserver and ASP.NET MVC provides various options to redirect a user.

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 TireDirect1
  3. In the middle frame of the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  4. In the Solution Explorer, right-click Content -> Add -> New Item ...
  5. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click Style Sheet
  6. Change the file Name to PayrollPreparation
  7. Click Add
  8. Create a few styles as follows:
    body {
    }
    
    .GroupBox {
        border-radius:    5px;
        padding:          10px;
        width:            375px;
        background-color: #E0DCCC;
        border:           2px solid #800000;
    }
    
    .GroupBox legend {
        border-radius:    5px;
        margin-left:      10px;
        font-size:        16px;
        width:            235px;
        color:            #E5DDAF;
        background-color: #6B2C3D;
        padding:          5px 15px;
        box-shadow:       0 0 0 5px #E5DDAF;
    }
    
    .GroupBox table {
        margin-bottom: 15px;
        margin-left:   15px;
    }
    
    .left-col { width: 135px; }
  9. In the Solution Explorer, expand Views and expand Shared
  10. Double-click _Layout.cshtml
  11. Include the style sheet as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tire Direct :: @ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link rel="stylesheet" type="text/css" href="~/Content/PayrollPreparation.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("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                    @Html.Partial("_LoginPartial")
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>&copy; @DateTime.Now.Year - Tire Direct</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  12. In the Solution Explorer, expand the Controllers folder and double-click HomeController.cs to open it
  13. Add two methods as follows:
    using System.Web.Mvc;
    
    namespace TireDirect1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult Create()
            {
                return View();
            }
    
            public ActionResult ShopTires()
            {
                return View();
            }
    
            public ActionResult StartPayroll()
            {
                return View();
            }
        }
    }
  14. In the Solution Explorer, below Views, right-click Home -> Add -> New Scaffolded Item...:
  15. In the middle frame of the Add Scasffold dialog box, click MVC 5 View and click Add
  16. Type StartPayroll as the name of the view
  17. Click Add
  18. Change the document as follows:
    @{
        ViewBag.Title = "Start Payroll";
    }
    
    <h2>Start Payroll</h2>
    
    <hr />
    
    @using (Html.BeginForm())
    {
        <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>Payroll #: @Html.TextBox("PayrollNumber")</td>
                <td><input type="submit" name="btnPreparePayroll" value="Prepare Payroll" style="width: 150px" /></td>
            </tr>
        </table>
    }
  19. In the Solution Explorer, below Views, right-click Home -> Add -> View...:
  20. Type Create as the name of the view
  21. Click Add
  22. To execute the application and test it, on the main menu, click Debug -> Start Without Debugging
  23. Close the browser and return to your programming environment

Redirecting a Response

Remember that the Internet Information Services (IIS) has its own library that contains a class named HttpResponse. On the other hand, ASP.NET provides the HttpResponseBase class that is an adaption of HttpResponse. To let you redirect a webpage visitor to a webpage, the Controller class is equpped with a property named Response. This property is of type HttpResponseBase:

public HttpResponseBase Response { get; }

Actually, this property gives you access to the members of its parent class. To let you redirect the visitors, the HttpResponse class is equipped with an overloaded method named Redirect. One of its versions uses the following syntax:

public void Redirect(string url);

To redirect visitors to a regular webpage (or website), pass its address as string. To redirect visitors to a view, pass its name to the method. Of course, the view and its action method must have been created.

ApplicationApplication: Redirecting a Response

  1. Click the HomeController.cs tab and add a method as follows:
    using System.Web.Mvc;
    
    namespace TireDirect1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult LearnMore()
            {
                return View();
            }
            
            public ActionResult Create()
            {
                return View();
            }
    
            public ActionResult ShopTires()
            {
                return View();
            }
    
            public ActionResult StartPayroll()
            {
                return View();
            }
        }
    }
  2. In the Solution Explorer, under Views, right-click Home -> Add -> View...
  3. Type LearnMore as the name of the view
  4. Click Add
  5. To execute the project, on the main menu, click Debug -> Start Without Debugging
  6. Close the browser and return to your programming environment
  7. Click the HomeController.cs tab and change the LearnMore() method as follows:
    using System.Web.Mvc;
    
    namespace TireDirect1.Controllers
    {
        public class HomeController : Controller
        {
            . . . No Change
    
            public ActionResult LearnMore()
            {
                Response.Redirect("https://en.wikipedia.org/wiki/Tire");
    
                return View();
            }
            
            . . . No Change
        }
    }
  8. Click the LearnMore.cshtml tab to activate it
  9. To execute the project, on the main menu, click Debug -> Start Without Debugging
  10. Close the browser and return to your programming environment

Redirection from a Controller

To support its own redirection, the System.Web.Mvc provides a class named RedirectResult. This is one of the classes derived from ActionResult.

Instead of making you go through the Response.Redirect() method to redirect your visitors, the Controller class is equipped with a method named Redirect. This method returns an object of type RedirectResult:

protected internal virtual RedirectResult Redirect(string url);

This method essentially works like the Response.Redirect() method. That is, it can take the address (URL) of a webpage or the name of a view as argument. Since the Controller.Redirect() method returns an ActionResult type of object, you can call it in place of View().

ApplicationPractical Learning: Redirecting from a Controller

  1. Click the HomeController.cs tab and change it as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace TireDirect1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                // Calling the Controller.Redirect() method to return an Controller.ActionResult-type of view
                return Redirect("Create");
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult LearnMore()
            {
                Response.Redirect("https://en.wikipedia.org/wiki/Tire");
    
                return View();
            }
    
            public ActionResult Create()
            {
                return View();
            }
    
            public ActionResult ShopTires()
            {
                // Calling the Controller.Redirect() method to return an Controller.ActionResult-type of object
                return Redirect("https://en.wikipedia.org/wiki/Shopping");
            }
    
            public ActionResult StartPayroll()
            {
                return View();
            }
        }
    }
  2. In the Solution Explorer, below Views and below Home, double-click Index to open it
  3. To execute, on the main menu, click Debug -> Start Without Debugging
  4. Close the browser and return to your programming environment
  5. In the Solution Explorer, below Views, right-click Home -> Add -> View...
  6. Type Index as the name of the view
  7. Click Add
  8. To execute, on the main menu, click Debug -> Start Without Debugging
  9. Close the browser and return to your programming environment

Redirection to an Action

In ASP.NET MVC, the Controller class makes it very easy to move from one view to another. One more way the class supports this operation is through an overloaded method named RedirectToAction. This method too returns an ActionResult type of object. As a result, you can call it in place of View().

The simplest version of the Controller.RedirectToAction() takes a string as argument. In this case, pass the name of an action as argument. If you do, when it comes time to redirect, the compiler will look for the view in the same controller as the method that called. If there is no such a view, the browser would display an error. If the view is in a different controller, the Controller provides another version of the RedirectToAction() method that takes two string arguments. When calling it, pass the name of the view and the name of the controller as arguments in that order.

Practical LearningPractical Learning: Redirecting to an Action

  1. Access the HomeContoller.cs tab and change it as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace TireDirect1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                // Calling the Controller.Redirect() method to return an Controller.ActionResult-type of view
                return Redirect("Create");
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult LearnMore()
            {
                Response.Redirect("https://en.wikipedia.org/wiki/Tire");
    
                return View();
            }
    
            public ActionResult Create()
            {
                return RedirectToAction("StartPayroll");
            }
    
            public ActionResult ShopTires()
            {
                // Calling the Controller.Redirect() method to return an Controller.ActionResult-type of object
                return Redirect("https://en.wikipedia.org/wiki/Shopping");
            }
    
            public ActionResult StartPayroll()
            {
                return View();
            }
        }
    }
  2. Click the Create.cshtml tab to access it
  3. To execute the project, on the main menu, click Debug -> Start Without Debugging
  4. Close the browser and return to your programming environment
  5. Close your programming environment

Previous Copyright © 2017-2019, FunctionX Next