Detailed description of the ASP (mvc--Controller)

Source: Internet
Author: User
Tags what is asp

1. Understanding the Controller

The MVC Controller is responsible for responding to requests originating from an ASP. NET MVC Web site. Each browser request is mapped to a dedicated controller. For example, imagine that you entered the following URL in the browser's address bar:

Localhost/product/index/3

In this case, a controller named Productcontroller will be called. The Productcontroller is responsible for generating responses to browser requests. For example, a controller might return a specific view, or redirect the user to another controller.

You can create a new controller by adding a new controller under the Controllers folder in the ASP. NET MVC application. Right-click on the Controller's folder and select the menu item "Add", "new", and select "MVC controller Class" (see Figure 1). The name of the controller must contain the controllers suffix. For example, controller name Productcontroller is fine, but controller product does not work.

If you create a new controller named Productcontroller, you will get the file shown in Listing 1.

Code Listing 1–productcontroller.cs

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcapp.controllers{public     class Productcontroller:controller     {public          actionresult Index ()          {               ADD action logic here               throw new NotImplementedException ();}}}     

As you can see in Listing 1, the controller is just a class (Visual Basic.NET or C # Class). A controller is a class that inherits from the System.Web.Mvc.Controller base class. Because the controller inherits from this base class, the controller easily inherits some useful methods (we will discuss these methods shortly).

2. Understanding the Controller action

The controller is exposed to the controller action. Action is a method of the controller that will be called when you enter a specific URL in the browser's address bar. For example, suppose you make a request to the following URL:

Localhost/product/index/3

In this example, the Index () method is called on the Productcontroller class. The Index () method is an example of a controller action.

A controller action must be a public method of the Controller class. The C # method, by default, is a private method. Realize that any public method you add to the Controller class will automatically be exposed as a controller action (you must be very careful, because the controller action can be called by anyone worldwide, simply by entering the correct URL in the browser address bar).

The controller action also needs to meet some additional requirements. The method used as a controller action cannot be overloaded. In addition, the controller action cannot be a static method. In addition to these, you can use any method as a controller action.

3. Understanding Controller Results

The controller action returns something called the action result. The action result is something that the controller action returns to the browser request.

The ASP. NET MVC Framework supports six standard types of action results:

viewresult– represents HTML and markup.

emptyresult– represents no results.

The redirectresult– delegate redirects to a new URL.

The redirecttorouteresult– represents a redirect to a new controller action.

jsonresult– represents a JSON (Javascript Object Notation) result that can be used in AJAX applications.

contentresult– represents the text result.

All of these action results are inherited from the ActionResult base class.

In most cases, the controller action is ViewResult. For example, the index () controller action in Code Listing 2 returns a Viewresult.

Code Listing 2–bookcontroller.cs

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcapp.controllers{public     class Bookcontroller:controller     {public          actionresult Index ()          {               return View ();}}     }

When an action returns a Viewresult, the HTML will be returned to the browser. The index () method in code Listing 2 returns a view named Index.aspx to the browser.

Notice that the index () action in Listing 2 does not put back a viewresult (). Instead, the view () method of the Controller base class is called. Typically, you do not return an action result directly. Instead, call the Controller base class in one of the following ways:

view– returns a viewresult result.

redirect– returns a Redirectresult action result.

redirecttoaction– returns a redirecttoaction action result.

redirecttoroute– returns a Redirecttoroute action result.

json– returns a Jsonresult action result.

content– returns a Contentresult action result.

So, if you want to return a view to the browser, you can call the view () method. If you want to drop the user from one controller action to another, you can call the Redirecttoaction () method. For example, the details () action in Code Listing 3 either displays a view or redirects the user to the index () action, depending on whether the ID parameter contains a value.

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcapp.controllers{public     class Customercontroller:controller     {public          actionresult Details (int? ID)          {               if (id = = NULL)                    return redirecttoaction ("Index");               return View ();          }          Public ActionResult Index ()          {               return View ();}}     }

Contentresult action results are very special. You can use the Contentresult action result to return an action result as plain text. For example, the index () method in Listing 4 returns the message as plain text instead of HTML.

Code Listing 4–statuscontroller.cs

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcapp.controllers{public     class Statuscontroller:controller     {public          contentresult Index ()          {               Return Content ("Hello world!");}}}     

When the Statuscontroller.index () action is called, a view is not returned. Instead, the original text "Hello world!" is returned to the browser. ”。

If a controller action returns a result that is not a result of an action-for example, a date or an integer-then the result is automatically wrapped in Contentresult. For example, when calling the index () action of Workcontroller in Listing 5, the date is automatically returned as a contentresult.

Code Listing 5–workercontroller.cs

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcapp.controllers{public     class Workcontroller:controller     {public          DateTime Index ()          {               return DateTime.Now;}}     }

The index () action in Code Listing 5 returns a DateTime object. The ASP. NET MVC framework automatically converts a DateTime object to a string and wraps the datetime value in a contentresult. The browser will receive the date and time in plain text.

4. Summary

The purpose of this tutorial is to introduce you to the concepts of controller, controller action, and controller action results in ASP. In the first section, you learned how to add a new controller to an ASP. NET MVC project. Next, you learn how the public method of the controller is exposed to the world as a controller action. Finally, we discuss the various types of action results that can be returned from the controller action. In particular, we discussed how to return a Viewresult, Redirecttoactionresult, and Contentresult from the controller action.

5. Create a Controller

The purpose of this tutorial is to explain how to create a new ASP. NET MVC Controller. You will learn how to create a controller by using the visual Studio ADD Controller menu and manually creating a class file.

5.1 Using the Add controler menu option

The simplest way to create a new control is to right-click on the Controllers folder of the solution browser in Visual Studio and select the Add,controller menu item (1). Select this menu item to open the Add Controller dialog box (2).

Figure 2: Adding a new controller

Notice that the first part of the controller name is highlighted in the Add Controller dialog box. The name of each controller must end with the controller suffix. For example, you can create a controller called Productcontroller, but you cannot create a controller called product.

Note: If you create a controller that does not contain the controller suffix, then you will not be able to invoke this control. Don't do that-I've wasted countless hours after making this mistake.

Code Listing 1-controller/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:/product/public        actionresult Index ()        {            return View ();    }}}

You should always create a controller in the Controllers folder. Otherwise, the practice of ASP. NET MVC is compromised, and other programmers will spend more time understanding your application.

5.2 Creating an action method

When you create a controller, you have the option to automatically generate create,update and details action methods (3). If you choose this option, the controller class in code 2 is generated.


Code Listing 2-controllers\customercontroller.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 Customercontroller:controller {//        GET:/customer/public actionresult Index () {return View (); }///GET:/CUSTOMER/DETAILS/5 public actionresult Details (int id) {return View (        );        }///GET:/customer/create public ActionResult Create () {return View (); }////POST:/customer/create [Acceptverbs (httpverbs.post)] public actionresult Create (Form Collection Collection) {try {//Todo:add insert logic here R            Eturn redirecttoaction ("Index");            } catch {return View (); }}////GET:/CUSTOMER/EDIT/5        Public ActionResult Edit (int id) {return View (); }////POST:/CUSTOMER/EDIT/5 [Acceptverbs (httpverbs.post)] public actionresult Edit (int id,                 FormCollection collection) {try {//Todo:add update logic here            Return redirecttoaction ("Index");            } catch {return View (); }        }    }}

These generated methods are just some stub methods (stub methods). You must add the actual logic for the customer's creation, update, and display details yourself. However, these stub methods provide a nice starting point for you.

5.3 Creating a Controller class

The ASP. NET MVC controller is just a class. If you like, you can create a controller class yourself manually by ignoring Visual Studio's convenient way to create a controller. Follow these steps:

Right-click the Controllers folder and select menu item add,new Item, then select the class template.

Name the new class PersonController.cs, and then click the Add button.

Modify the resulting class file so that the class inherits from the System.Web.Mvc.Controller base class (see Listing 3).

Code Listing 3-controllers\personcontroller.cs

Using system;using system.collections.generic;using system.linq;using system.web;namespace mvcapplication1.controllers{public    class PersonController:System.Web.Mvc.Controller    {public        string Index ()        {            return "Hello world!";}}    }

The controller class in Code Listing 3 publishes an action called Index (), which returns the string "Hello world! ”。 You can invoke this controller action by running the application and requesting a URL like this:

Localhost:40071/person

The NOTE:ASP.NET development server uses a random port number (for example, 40071). When you enter a URL to invoke the controller, you need to provide the correct port number. You can get the port number by hovering the mouse over the icon of the ASP. In Windows Notification area (the lower-right corner of the screen).

6. Create a custom action

The purpose of this tutorial is to explain how to create a new controller action. You will learn the requirements of the Controller action. You will also learn how to prevent the method from being advertised as a controller action.

6.1 Adding actions to the controller

You can add a new action to the controller by adding a new method to the controller. For example, the controller in Code Listing 1 contains an action called Index () and a SayHello (). Both of these methods are advertised for action.

Code Listing 1-controllers\homecontroller.cs

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace mvcapplication1.controllers{    [HandleError] public    class Homecontroller:controller    {        public ActionResult Index () {            return View ();        }        public string SayHello () {            return ' hello! ';        }}        }

In order to publish the method as an action to the world, the method must meet certain requirements:

The method must be public.

Method cannot be a static method.

Method cannot make an extension method.

The method cannot be a constructor, an accessor, or a set.

Method cannot have an open generic type (open generic types).

Method cannot make a method in a controller base class.

The method cannot contain a ref or out parameter.

6.2 Blocking public methods from being called

If you need to create a public method in the controller, but you do not want to publish this method as a controller action, you can prevent the method from being called by the outside world by using the [nonaction] attribute. For example, the controller in Code Listing 2 contains a public method called Companysecrets (), which is decorated with the [nonaction] feature.

Code Listing 2-controller\workcontroller.cs

Using System.web.mvc;namespace mvcapplication1.controllers{public    class Workcontroller:controller    {        [ Nonaction] public        string companysecrets ()        {            Return ' This information is secret. ';}}    }

If you attempt to invoke the Companysecrets () controller action by entering/work/companysecrets in the browser address bar, you will get the error message shown in Figure 5:

"Recommended"

1. What is ASP. NET MVC? Summarizing ASP. NET MVC

2. Learn more about the difference between ASP. NET MVC and WebForm

3. Detailed description of the ASP. mvc--View

4. Detailed description of ASP. mvc--Routing

5. Code examples for developing custom menu editing tools with ASP.

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.