ASP. net mvc controller Overview (C #)

Source: Internet
Author: User

This tutorial discusses ASP. net mvc controller, controller action, and action result. After completing this tutorial, you will understand how controllers are used to control the interaction between visitors and ASP. net mvc websites.

Understanding Controller

The MVC Controller is responsible for responding to ASP. net mvc website requests. Each browser request is mapped to a specific controller. For example, enter the following URL in the address bar of your browser:

Http: // localhost/product/index/3

In this case, the Controller named productcontroller is called. Productcontroller is responsible for generating responses to browser requests. For example, the Controller returns a specific view to the browser or redirects the user to another controller.

Code 1 contains a simple controller named productcontroller.

Code 1-controllers/productcontroller. CS

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Mvc.Ajax;namespace MvcApplication1.Controllers{    public class ProductController : Controller    {        //        // GET: /Products/        public ActionResult Index()        {            // Add action logic here            return View();        }    }}

As you can see in code 1, the controller is just a class (A Visual Basic. Net or C # class ). The Controller inherits the base class system. Web. MVC. controller. Since the Controller inherits this base class, it inherits several useful methods (we will discuss these methods later ).

Understanding controller actions

The Controller exposes actions. An action is a method on the controller. It is called when a specific URL is entered in the browser address bar. For example, imagine sending the following URL request:

Http: // localhost/product/index/3

In this case, the index () method on the productcontroller class is called. The index () method is an example of the controller action.

The Controller action must be a public method of the controller class. C # The method is private by default. Note that any public method added to the Controller class will be automatically exposed as the controller action (you must be careful, because anyone who enters the correct URL in the browser address bar can call the Controller action ).

Several additional requirements are required to meet the Controller action. The method used as the controller action cannot be overloaded. Also, the Controller action cannot be a static method. Other methods can be used as the controller action.

Understanding action result

The Controller action returns someAction result. Action result is the response of the controller action to the browser request.

The ASP. net mvc Framework supports centralized action results, including:

  1. Viewresult-Indicates HTML and tags.
  2. Emptyresult-indicates no result.
  3. Redirectresult-Indicates redirecting to another URL
  4. Jsonresult-indicates the JavaScript Object symbol (JSON) that can be used for Ajax programs ).
  5. Contentresult-indicates the text result.
  6. Filecontentresult-indicates a downloadable file (Binary ).
  7. Filepathresult-indicates the file to be downloaded (PATH ).
  8. Filestreamresult-indicates the file that can be downloaded (file stream ).

All these actions are inherited from the actionresult base class.

In most cases, the Controller action returns a viewresult. For example, code 2:

Code 2-controllers/bookcontroller. CS

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Mvc.Ajax;namespace MvcApplication1.Controllers{    public class BookController : Controller    {        public ActionResult Index()        {            // Add action logic here            return View();        }    }}

When action returns a viewresult, HTML returns to the browser. The index () method in Code 2 returns a view named index to the browser.

Note that the index () Action in Code 2 does not return viewresult (), but calls the view () method of the controller base class. Generally, the action result is not directly returned, but one of the following controller base class methods is called:

  1. View-returns a viewresult action result.
  2. Redirect-returns a redirectresult action result.
  3. Redirecttoaction-returns a redirecttoaction action result.
  4. Redirecttoroute-returns a redirecttorouteresult action result.
  5. JSON-return a jsonresult action result.
  6. Javascriptresult-A javascriptresult is returned.
  7. Content-returns a contentresult action result.
  8. File-A filecontentresult, filepathresult, or filestreamresult is returned, depending on the parameters of the input method.

Therefore, if you want to return a View to the browser, you can call the view () method. To redirect a user from one controller action to another, call the redirecttoaction () method. For example, the details () Action in code 3 shows a view or redirects the user to the index () Action, depending on whether the ID parameter has a value.

Code 3-customercontroller. CS

using System.Web.Mvc;namespace MvcApplication1.Controllers{    public class CustomerController : Controller    {        public ActionResult Details(int? id)        {            if (!id.HasValue)                return RedirectToAction("Index");            return View();        }        public ActionResult Index()        {            return View();        }    }}

Contentresult action result is special. You can use contentresult action result to return an action result in plain text. For example, the index () method in code 4 returns plain text instead of HTML.

Code 4-controllers/statuscontroller. CS

using System.Web.Mvc;namespace MvcApplication1.Controllers{    public class StatusController : Controller    {        public ActionResult Index()        {            return Content("Hello World!");        }    }}

When statuscontroller. Index () action is called, a plain text "Hello World!" is returned instead of a view! "To the browser.

If the Controller action returns a result that is not the action result-for example, a date or an integer-the result is automatically encapsulated into contentresult. For example, when the index () Action of workcontroller in code 5 is called, the date is automatically returned as contentresult.

Code 5-workcontroller. CS

using System;using System.Web.Mvc;namespace MvcApplication1.Controllers{    public class WorkController : Controller    {         public DateTime Index()        {            return DateTime.Now;        }    }}

The index () Action in code 5 returns a datetime object. ASP. net mvc Framework converts datetime objects to strings and automatically encapsulates datetime values into contentresult. The browser receives the date and time in plain text format.

Summary

This tutorial aims to introduce the concepts of ASP. net mvc controller, controller action, and controller action result. In section 1, you learned how to add a new controller to the ASP. net mvc program. Then, you learned how the Controller's public method is exposed as the controller action. Finally, we discuss the different types of action results that can be returned from the Controller action. In particular, we have discussed how to return a viewresult, redirecttoactionresult, and contentresult from the Controller action.

Address: http://www.asp.net/learn/mvc/tutorial-03-cs.aspx

Related Article

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.