Controller and Action Method
Original article: http://quickstarts.asp.net/3-5-extensions/mvc/MVCControllerActions.aspx
1. Introduction
Responsibilities of the Controller: locate and execute the action method, and ensure that it can be correctly executed; Obtain and pass the parameters required by the Action method to it; capture errors that occur during the execution of the Action method; provide" Webformviewfactory Class to generate views of ASP. NET page types.
A simple example:
namespace mvcapplication. controllers
{< br id = "p8hs4"> public class homecontroller: controller
{< br id = "p8hs6"> Public void index ()
{< br id = "p8hs8"> renderview ("Index ");
}< br id = "p8hs10">
Public void about ()
{
viewdata ["companyName"] = "contoso ";
renderview ("about ");
}< br id = "p8hs16" >}< br id = "p8hs17" >}
2. Action Method
By default, the MVC framework considers all public methods as action methods. If you do not want to make a public method an action method, you should use"Nonactionattribute"Property tag.
3. Parameters of the Action Method
By default, the parameters of the Action method are a set of key-value pairs from form, query string, and cookie.
Controller base classThe Controller is responsibleTheThe parameter is passed to the action method. When the parameter value cannot be parsed, if the parameter is referenced or nullable type, null is passed to it; otherwise, an exception is thrown.
To directly access the data in the URL, the Controller provides the request and response classes. Their semantics correspondsHttprequestAndHttpresponse. The following is a simple example:
Public void detail ()
{
Int id = convert. toint32 (request ["ID"]);
}
4. Automatically map parameters of the Action Method
When an HTTP request contains a parameter with the same name as the parameter of the Action method, the value of this parameter is automatically passed to the action method. In addition, the MVC framework also supports optional parameters. When the parameter of the Action method is of the nullable type and is passed to any value of this parameter, the Controller will pass null to this parameter. The following is an example:
Public void showarticles (datetime date)
{
If (! Date. hasvalue)
{
Date = datetime. now;
}
//...
}
5. process unknown actions
When the controller processes an unknown action, it will throwHandleunknownaction exception. The default Processing Method of the controller is to returnAn HTTP 404 error occurs. In addition, you can rewrite"HandleunknownerrorTo handle custom errors. The following is an example:
Public void override handleunknownerror (string action) {
// redirect to a search page where the unknown action is
// The search query. determine when to show the search page
// based on the result of calling a shouldshowsearch () method.
If (shouldshowsearch (Action) = true)
{< br id = "iwf98"> redirecttoaction ("Search", action);
return;
}< br id = "iwf911"> base. handleunknownerror (action);
}< br id = "iwf913">