Controlling the Views in ASP.NET MVC
Controlling the Views in ASP.NET MVC
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 Learning: Introducing Controllers
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;
}
}
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");
}
}
}
. . . 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 Learning: Specifying the Title of a Web Page
@{
ViewBag.Title = "Payroll Preparation";
}
<h2>Payroll Preparation</h2>
@using (Html.BeginForm("PayrollSummary", "Home", FormMethod.Post, new { name="frmPayroll" }))
{
}
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 Learning: Preparing Values for a Form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PayrollPreparation13.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 PayrollPreparation()
{
return View();
}
public ActionResult PayrollSummary(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("F");
ViewBag.MondayOvertime = wdMonday.Overtime.ToString("F");
ViewBag.MondayRegularPay = wdMonday.RegularPay.ToString("F");
ViewBag.MondayOvertimePay = wdMonday.OvertimePay.ToString("F");
ViewBag.TuesdayRegularTime = wdTuesday.RegularTime.ToString("F");
ViewBag.TuesdayOvertime = wdTuesday.Overtime.ToString("F");
ViewBag.TuesdayRegularPay = wdTuesday.RegularPay.ToString("F");
ViewBag.TuesdayOvertimePay = wdTuesday.OvertimePay.ToString("F");
ViewBag.WednesdayRegularTime = wdWednesday.RegularTime.ToString("F");
ViewBag.WednesdayOvertime = wdWednesday.Overtime.ToString("F");
ViewBag.WednesdayRegularPay = wdWednesday.RegularPay.ToString("F");
ViewBag.WednesdayOvertimePay = wdWednesday.OvertimePay.ToString("F");
ViewBag.ThursdayRegularTime = wdThursday.RegularTime.ToString("F");
ViewBag.ThursdayOvertime = wdThursday.Overtime.ToString("F");
ViewBag.ThursdayRegularPay = wdThursday.RegularPay.ToString("F");
ViewBag.ThursdayOvertimePay = wdThursday.OvertimePay.ToString("F");
ViewBag.FridayRegularTime = wdFriday.RegularTime.ToString("F");
ViewBag.FridayOvertime = wdFriday.Overtime.ToString("F");
ViewBag.FridayRegularPay = wdFriday.RegularPay.ToString("F");
ViewBag.FridayOvertimePay = wdFriday.OvertimePay.ToString("F");
return View("PayrollPreparation");
}
}
}
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 Learning: Accessing the Values from an Action
@{
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> </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> </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>
}
Hourly Salary: 26.68 Monday: 8 Tuesday: 10.5 Wednesday: 6.5 Thursday: 9.5 Friday: 7
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 Learning: Setting the Width of a Form
using System; using System.Web.Mvc; namespace PayrollPreparation13.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 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("F"); ViewBag.MondayOvertime = wdMonday.Overtime.ToString("F"); ViewBag.MondayRegularPay = wdMonday.RegularPay.ToString("F"); ViewBag.MondayOvertimePay = wdMonday.OvertimePay.ToString("F"); ViewBag.TuesdayRegularTime = wdTuesday.RegularTime.ToString("F"); ViewBag.TuesdayOvertime = wdTuesday.Overtime.ToString("F"); ViewBag.TuesdayRegularPay = wdTuesday.RegularPay.ToString("F"); ViewBag.TuesdayOvertimePay = wdTuesday.OvertimePay.ToString("F"); ViewBag.WednesdayRegularTime = wdWednesday.RegularTime.ToString("F"); ViewBag.WednesdayOvertime = wdWednesday.Overtime.ToString("F"); ViewBag.WednesdayRegularPay = wdWednesday.RegularPay.ToString("F"); ViewBag.WednesdayOvertimePay = wdWednesday.OvertimePay.ToString("F"); ViewBag.ThursdayRegularTime = wdThursday.RegularTime.ToString("F"); ViewBag.ThursdayOvertime = wdThursday.Overtime.ToString("F"); ViewBag.ThursdayRegularPay = wdThursday.RegularPay.ToString("F"); ViewBag.ThursdayOvertimePay = wdThursday.OvertimePay.ToString("F"); ViewBag.FridayRegularTime = wdFriday.RegularTime.ToString("F"); ViewBag.FridayOvertime = wdFriday.Overtime.ToString("F"); ViewBag.FridayRegularPay = wdFriday.RegularPay.ToString("F"); ViewBag.FridayOvertimePay = wdFriday.OvertimePay.ToString("F"); return View(); } } }
@{ 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"> </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"> </td> <td><input type="submit" name="btnPrepararePayroll" style="width: 400px" value="Preparare Payroll" /></td> </tr> </table> }
@{ 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> </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> </td> <td colspan="5" style="text-align: center; height: 32px;"><input type="submit" name="btnCalculate" style="width: 400px" value="Calculate" /></td> </tr> </table> }
Hourly Salary: 16.57 Monday: 7.5 Tuesday: 12 Wednesday: 9.5 Thursday: 8 Friday: 6.5
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 Learning: Generating a Models Folder
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; }
<!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>© @DateTime.Now.Year - Tire Direct</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
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();
}
}
}
@{ 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> }
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.
Application: Redirecting a Response
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();
}
}
}
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
}
}
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().
Practical Learning: Redirecting from a Controller
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(); } } }
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 Learning: Redirecting to an Action
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();
}
}
}
|
||
Previous | Copyright © 2017-2019, FunctionX | Next |
|