Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Controller in ASP.NET MVC

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of the controller in ASP.NET MVC, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

1. Understand the controller

The MVC controller is responsible for responding to requests made to the ASP.NET MVC website. Each browser request is mapped to a dedicated controller. For example, imagine that you enter the following URL in the browser address bar:

Localhost/product/index/3

In this case, a controller named ProductController will be invoked. 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 of the ASP.NET MVC application. Right-click the folder of the controller, and select the menu items "Add", "New", and select "MVC Controller Class (MVC Controller Class)" (see figure 1). The name of the controller must have a Controller suffix. For example, there is nothing wrong with the controller name ProductController, but the controller Product does not work.

If you create a new controller called ProductController, you will get the file shown in listing 1.

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 (which we will discuss shortly).

two。 Understand the controller action

The controller exposes the controller action. An 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 for 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 private.

The controller action also has 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. Apart from these, you can use any method as a controller action.

3. Understand the controller result

The controller action returns something called the Action Result of the action. The result of the action is what the controller action returns to the browser request.

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

ViewResult-stands for HTML and markup.

EmptyResult-stands for no result.

RedirectResult-represents a redirect to a new URL.

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 result of the text.

The results of all these actions are inherited from the ActionResult base class.

In most cases, the controller acts ViewResult. For example, the Index () controller action in listing 2 returns a ViewResult.

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, it returns HTML to the browser. The Index () method in 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. Usually, you don't directly return the result of an action. Instead, one of the following methods of the Controller base class is called:

View-returns a ViewResult result.

Redirect-returns the result of a RedirectResult action.

RedirectToAction-returns the result of a RedirectToAction action.

RedirectToRoute-returns the result of a RedirectToRoute action.

Json-returns the result of a JsonResult action.

Content-returns the result of a ContentResult action.

So, if you want to return a view to the browser, you can call the View () method. If you want to redirect user actions from one controller to another, you can call the RedirectToAction () method. For example, the Details () action in 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 ();}

The result of ContentResult action is very special. You can use the ContentResult action result to return the action result as plain text. For example, the Index () method in listing 4 returns the message as plain text instead of HTML.

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, no view is returned. Instead, the original text "Hello World!" was 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 the Index () action of WorkController in listing 5 is called, the date is automatically returned as a ContentResult.

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 listing 5 returns a DateTime object. The ASP.NET MVC framework automatically converts the 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 controllers, controller actions, and controller action results in ASP.NET MVC. In the first part, you learned how to add a new controller to the ASP.NET MVC project. Next, you learned how the common methods of controllers are exposed to the world as controller actions. Finally, we discuss the different types of action results, which can be returned from the controller actions. 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 controllers through the Visual Studio Add Controller menu and manually creating class files.

5.1 use Add Controler menu options

The easiest way to create a new control is to right-click on the Controllers folder in Visual Studio's solution browser and select the Add,Controller menu item (figure 1). Selecting this menu item opens the Add Controller dialog box (figure 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, you will not be able to call the controller. Don't do this-I've wasted a lot of time since I made this mistake.

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, it will break the ASP.NET MVC convention, and other programmers will spend more hard time understanding your application.

5.2 create an action method

When you create a controller, you can choose to automatically generate Create,Update and Details actions (see figure 3). If you select this option, the controller class in Code 2 will be generated.

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 (FormCollection collection) {try {/ / TODO: Add insert logic here return 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 stub methods (stub methods). You must add actual logic to the customer's creation, update, and display details yourself. However, these stub methods provide you with a beautiful starting point.

5.3 create a controller class

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

Right-click the Controllers folder and select the menu item Add,New Item, and 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).

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 listing 3 exposes 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 type URL to call the controller, you need to provide the correct port number. You can get the port number by hovering over the icon on the ASP.NET development server, which is located in the Windows Notification Area (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 published as a controller action.

6.1 add actions to the controller

You can add new actions to the controller by adding a new method to the controller. For example, the controller in listing 1 contains an action called Index () and an action called SayHello (). Both methods are published for action.

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 to the world as an action, the method must meet specific requirements:

The method must be public.

Method cannot be static.

Method cannot extend the method.

Method cannot be a constructor, accessor, or setter.

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

Method cannot make the method in the controller base class.

Methods cannot contain ref or out parameters.

6.2 prevent public methods from being called

If you need to create a public method in the controller, but you don't want to publish the method as a controller action, you can prevent the method from being called by the outside world by using the [NonAction] feature. For example, the controller in listing 2 contains a public method called CompanySecrets (), which is decorated with the [NonAction] feature.

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 try to invoke the CompanySecrets () controller action by typing / Work/CompanySecrets in the browser address bar, you will get the error message shown in figure 5:

Thank you for reading this article carefully. I hope the article "sample Analysis of controllers in ASP.NET MVC" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report