Creating a Controller with IController
All controller classes must Implemet IController interface.
Public classBasiccontroller:icontroller { Public voidExecute (RequestContext requestcontext) {stringController = (string) requestcontext.routedata.values["Controller"]; stringAction = (string) requestcontext.routedata.values["Action"]; RequestContext.HttpContext.Response.Write (string. Format ("Controller is {0} with action is {1}", controller, Action)); } }
Creating a controller by deriving from the controller Class
Compared with class-Implement IController interface, class derived from Controller class have three key features:
- Action method:a controller ' s behavior is partitioned to multiple methods (instead of having just one single Execute () m Ethod). Each method was exposed on a different URL and was invoked with parameters extracted from the incoming request.
- Actioin Result:you can return an object describing the Result of a action, which was then carried off on your behalf.
- Filter:you can encapsulate reusable behaviors (for example, authentication) as filters, and then tags each behavior onto o NE or more controllers or action methods by putting a attribute in your source code.
Public class Defaultcontroller:controller { // get:default Public actionresult Index () { return View (); } }
Receiving Request Data
There is three main to access data:
- Extract it from a set of context objects.
- The data passed as parameters to your action method.
- Explicitly invoke the framework ' s model binding feature.
Getting Data from the context Objects, below is commonly used Context Objects and properties:
Httpcontext.response, HttpContext.Request, Httpcontext.session, HttpContext.User, Httpcontext.cache, Httpcontext.application, Httpcontext.items, Httpcontext.server, Routedata.values, TempData.
Understanding Action Results
When the MVC Framework receives a ActionResult object from a action method, it calls the Executeresult method defined by That object. The action result implementation then deals with the Response object for you, generating the output that corresponds to Yo ur intention.
Built-in Action Result Type:
Returning HTML by Rendering a View
When the MVC Framework calls the Executeresult method of the ViewResult object, a search would begin for the view this have specified. If you is using areas in your project and then the framework would look in the following locations:
? /areas/<areaname>/views/<controllername>/<viewname>.aspx
? /areas/<areaname>/views/<controllername>/<viewname>.ascx
? /areas/<areaname>/views/shared/<viewname>.aspx
? /areas/<areaname>/views/shared/<viewname>.ascx
? /areas/<areaname>/views/<controllername>/<viewname>.cshtml
? /areas/<areaname>/views/<controllername>/<viewname>.vbhtml
? /areas/<areaname>/views/shared/<viewname>.cshtml
? /areas/<areaname>/views/shared/<viewname>.vbhtml
The MVC Framework checks to see if all of these files exists in turn. As soon as it locates a match, it uses that view to render the result of the action method.
If you were not using areas, or you were using areas but none of the files in the preceding list has been found, then the F Ramework continues its search, using the following locations:
? /views/<controllername>/<viewname>.aspx
? /views/<controllername>/<viewname>.ascx
? /views/shared/<viewname>.aspx
? /views/shared/<viewname>.ascx
? /views/<controllername>/<viewname>.cshtml
? /views/<controllername>/<viewname>.vbhtml
? /views/shared/<viewname>.cshtml
? /views/shared/<viewname>.vbhtml
Passing Data from an Action Method to a View
Providing a View Model Object
Passing Data with the View Bag
Performing redirections
Redirecting to a Literal URL
Public Redirectresult Redirect () { return redirectpermanent ("/example/index" );}
Redirecting to a Routing System URL
Public Redirecttorouteresult Redirect () { return redirecttoroute (new { " Example " , " Index " , " MyID " });}
Redirecting to an Action Method
Public Redirecttorouteresult Redirect () { return redirecttoaction ("Index" );}
A redirection causes the browser to submit a entirely new HTTP request, which means the Tails of the original request. If you want to pass data from one request to the next, you can use the Temp data feature. TempData is similar to Session data, except that TempData values was marked for deletion when they was read, and they are Removed when the request has been processed.
PublicRedirecttorouteresult Redirecttoroute () {tempdata["Message"] ="Hello"; tempdata["Date"] =DateTime.Now; returnRedirecttoaction ("Index");} PublicViewResult Index () {viewbag.message= tempdata["Message"]; Viewbag.date= tempdata["Date"]; returnView ();}
You can get a value from TempData without marking it for removal is using the Peek method, like this:
DateTime time = (datetime) Tempdata.peek ("Date");
You can preserve a value that would otherwise is deleted by using the Keep method, such as this:
Tempdata.keep ("Date");
The Keep method doesn ' t protect a value forever. If The value is read again, it'll be marked for removal once more.
Returning Errors and HTTP Codes
Sending a specific HTTP Result Code
Public Httpstatuscoderesult StatusCode () { returnnew httpstatuscoderesult (404 " URL cannot be serviced " );}
Sending a 404 Result
Public Httpstatuscoderesult StatusCode () { return httpnotfound ();}
Sending a 401 Result
Public Httpstatuscoderesult StatusCode () { returnnew httpunauthorizedresult ();}
ASP. NET MVC 5 Controllers and Actions