ASP. NET MVC Controllers and Actions

Source: Internet
Author: User

The URL requests in the MVC application are handled through the controller controllers, whether the GET request for the view page is requested, or the post request that passes the data to the server processing is handled by an controller, looking first at a simple controlller:

public class derivedcontroller:controller{Public    actionresult Index ()    {        viewbag.message = ' Hello from the ' Derivedcontroller Index method ";   Dynamic Data        return View ("MyView");   Specify the returned view    }}

is a derivedcontroller, then the corresponding processing URL is this: Localhost:1042/derived/index, and the index action specifies that the returned view is MyView, not the same name as the Index view, Then you need to create a new view myview. Right-add view-MyView in the index action method, or create a new derived directory under the views directory of the solution, then right-new view-MyView:

@{    viewbag.title = "MyView";} 

Direct Ctrl+f5 The URL that the browser navigates to is: localhost:1042, look at the definition of the route:

Routes. MapRoute (    "Default",//route name    "{controller}/{action}/{id}",//URL with parameter    new {controller = "Home", action = "I Ndex ", id = urlparameter.optional}//parameter default value);

Note the last line of the route: new {controller = "Home", action = "Index", id = urlparameter.optional}
are given the default value, then url:localhost:1042 is actually: Localhost:1042/home/index ID is an optional parameter.
Localhost:1042/home/index this URL to find the controller is naturally homecontroller,index corresponds to the HomeController under the index of the action, Obviously no hoomecontroller, will naturally report 404 wrong.
Workaround:
1. Modify the default value of the route to:

New {controller = "Derived", action = "Index", id = urlparameter.optional}

2. Enter it manually in the URL bar of the browser: Localhost:1042/derived/index

You can take some parameters through the context object context:

String userName = user.identity.name;string ServerName = server.machinename;string ClientIP = request.userhostaddress;d Atetime datestamp = Httpcontext.timestamp;

As in normal WebForm, you can receive the passed parameters via Request.Form:

String oldproductname = request.form["Oldname"];string newproductname = request.form["NewName"];

Take the parameters in the URL/route:

String city = routedata.values["City"]. ToString ();

To pass a parameter to a controller:

Public ActionResult Showweatherforecast (String city, DateTime fordate) {    viewbag.city = city;    Viewbag.fordate = fordate;    return View ();}

The corresponding a tag is this:
@Html. ActionLink ("See Weather (Reference)", "Showweatherforecast", new {city = "Beijing", fordate = @DateTime. now})
Then add the corresponding view:

@{    Layout = null;} To query for: @ViewBag. City weather, check the time: @ViewBag. fordate

Running the next program Showweatherforecast view shows:
To be queried for: weather in Beijing, check-in time: 2013/11/25 21:08:04

Of course, you can not pass the parameter but provide the default value:

@Html. ActionLink ("View weather (default)", "Showweatherforecast", new {fordate = @DateTime. now})

No city, see Controller:

Public ActionResult Showweatherforecast (DateTime fordate, String city = "Hefei") {    viewbag.city = city;    Viewbag.fordate = fordate;    return View ();}

View Display:
To inquire: Weather in Hefei, check-in time: 2013/11/25 21:16:35
The default value already works.

Get the routing data in the controller:

public string Index () {    String controller = (string) routedata.values["Controller"];    String action = (string) routedata.values["action";    return string. Format ("controller: {0}, action: {1}", Controller, Action);}

The Natural browser will show: Controller:derived, Action:index
Action to implement the jump:

public void Index () {    Response.Redirect ("/derived/showweatherforecast");}

The use of Response.Redirect to achieve jump is also more biased webform, MVC should be so jump:

Public ActionResult Index () {    return new Redirectresult ("/derived/showweatherforecast");}

Before all are similar action is return of the view here but return is Redirectresult, this depends on the return value of the method, the return value of the method is ActionResult, and not just viewresult, It can be understood that ActionResult is the base class for Viewresult and Redirectresult and so on.
Here you can even return the physical path of the view file directly:

Return View ("~/views/derived/showweatherforecast.cshtml");

The commonly used action return value types are:

Jump to another action:

Public Redirecttorouteresult Redirect () {     

The method above is to jump to another action under the current controller, if you want to jump to an action in another controller:

Returns the normal text data:

Public Contentresult Index () {     String message = ' This is plain text ';     

Returns data in XML format:

Public Contentresult XMLData () {      storylink[] stories = Getallstories ();      XElement data = new XElement ("Storylist", stories. Select (E = {         return new XElement ("story",             New XAttribute ("title", E.title),             new XAttribute (" Description ", e.description),             new XAttribute (" link ", E.url));           

Return data in JSON format (common):

[HttpPost] public jsonresult jsondata () {      storylink[] stories = Getallstories ();     

File Download:

Public Fileresult Annualreport () {     string filename = @ "C:\AnnualReport.pdf";     String contentType = "Application/pdf";     String downloadname = "Annualreport2011.pdf";      

Triggering this action will return a file download prompt:

Return HTTP status code:

404 File Not Found public Httpstatuscoderesult StatusCode () {     return new Httpstatuscoderesult (404, "URL cannot is serviced") ; }//404 cannot find file public httpstatuscoderesult StatusCode () {     return httpnotfound ();} 401 Unauthorized public Httpstatuscoderesult StatusCode () {     return new Httpunauthorizedresult ();}

Back to RSS feed content:

Public Rssactionresult RSS () {     storylink[] stories = Getallstories ();     return new Rssactionresult<storylink> ("My Stories", Stories, E + = {         return new XElement ("Item",             new XAttribute ("title", E.title),             new XAttribute ("description", e.description),             new XAttribute ("link", E.url));     

Triggering this action will display the browser opportunity:

ASP. NET MVC Controllers and Actions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.