Detailed introduction to ASP.NET MVC--controller

零下一度
Release: 2017-05-20 13:33:49
Original
8713 people have browsed it

1. Understand the controller

MVCThe controller is responsible for responding to requests initiated to the ASP.NET MVC website. Every 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
Copy after login

In this case, a controller named ProductController will be called. 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 your ASP.NET MVC application. Right-click the controller's folder and select the menu items "Add", "New", and select "MVC Controller Class" (see Figure 1 ). The name of the controller must contain the suffix Controller. For example, the controller name ProductController is fine, but the controller Product does not work.

Detailed introduction to ASP.NET MVC--controller

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();
          }
     }
}
Copy after login

As you can see in Code Listing 1, a controller is just a class (Visual Basic.Net or C#kind). 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).

2. Understanding controller actions

Controllers expose controller actions. An action is a method of the controller that will be called when you enter a specific URL in the browser address bar. For example, suppose you make a request to the following URL:

localhost/Product/Index/3
Copy after login

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. C# methods, by default, are private methods. Realize that any public method you add to your controller class will automatically be exposed as a controller action (you have to be very careful as controller actions can be called by anyone in the world simply by typing the correct URL).

Controller actions also need to meet some additional requirements. Methods used as controller actions cannot be overloaded. Additionally, controller actions cannot be static methods. Apart from these, you can use any method as a controller action.

3. Understanding controller results

Controller actions return something called action results (Action Result). The action result is what the controller action returns to the browser for the request.

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

ViewResult – represents HTML and markup.

EmptyResult – represents no result.

RedirectResult – Represents a redirect to a new URL.

RedirectToRouteResult – Represents redirection to a new controller action.

JsonResult – Represents a JSON (Javascript Object Notation) result, which can be used in AJAX applications.

ContentResult – represents the text result.

All these action results inherit from the ActionResult base class.

In most cases, the controller acts ViewResult. For example, the Index() controller action in 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();
          }
     }
}
Copy after login

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

Notice that the Index() action in code listing 2 does not put back a ViewResult(). Instead, the View() method of the Controller base class is called. Normally, you don't return an action result directly. Instead, call one of the following methods of the Controller base class:

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 – 返回一个ContentResult动作结果。

因此,如果你想向浏览器返回一个视图,你可以调用View()方法。如果你想要降用户从一个控制器动作重定向到另一个,你可以调用RedirectToAction()方法。举个例子,代码清单3中的Details()动作要么显示一个视图,要么将用户重定向到Index()动作,取决于Id参数是否含有值。

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();
          }
     }
}
Copy after login

ContentResult动作结果很特别。你可以使用ContentResult动作结果来将动作结果作为纯文本返回。举个例子,代码清单4中的Index()方法将消息作为了纯文本返回,而不是HTML。

代码清单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!");
          }
     }
}
Copy after login

当调用StatusController.Index()动作时,并没有返回一个视图。而是向浏览器返回了原始的文本“Hello World!”。

如果一个控制器动作返回了一个结果,而这个结果并非一个动作结果 – 例如,一个日期或者整数 – 那么结果将自动被包装在ContentResult中。举个例子,当调用代码清单5中的WorkController的Index()动作时,日期将自动作为一个ContentResult返回。

代码清单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;
          }
     }
}
Copy after login

代码清单5中的Index()动作返回了一个DateTime对象。ASP.NET MVC框架自动将DateTime对象转换为一个字符串,并且将DateTime值包装在一个ContentResult中。浏览器将会以纯文本的方式收到日期和时间。

4. 总结

这篇教程的目的是为你介绍ASP.NET MVC中控制器、控制器动作以及控制器动作结果的概念。在第一部分,你学习了如何向ASP.NET MVC项目中添加新的控制器。接下来,你学习了控制器的公共方法是如何作为控制器动作暴露给全世界的。最后,我们讨论了动作结果的各种不同类型,这些动作结果可以从控制器动作中返回。特别地,我们讨论了如何从控制器动作中返回一个ViewResult、RedirectToActionResult和ContentResult。

5. 创建控制器

这篇教程的目的是解释如何来创建新的ASP.NET MVC控制器。你会学习如何通过Visual Studio Add Controller菜单和手工创建类文件,来创建控制器。

5.1 使用Add Controler菜单选项

创建一个新控制的最简单方法是在Visual Studio的解决方案浏览器的Controllers文件夹上点击右键,并且选择Add,Controller菜单项(如图1)。选择这个菜单项打开了Add Controller对话框(如图2)。

Detailed introduction to ASP.NET MVC--controller

图2:添加一个新的控制器

Detailed introduction to ASP.NET MVC--controller

注意到控制器名称的第一部分在Add Controller对话框中高亮显示了。每一个控制器的名称必须以Controller后缀结尾。举个例子,你可以创建一个叫做ProductController的控制器,但是不能创建一个叫做Product的控制器。

NOTE:如果你创建一个控制器,它不含有Controller后缀,那么你将无法调用这个控制器。不要这么做 -- 在犯了这个错误之后,我已经浪费了不计其数的时间。

代码清单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();
        }
    }
}
Copy after login

你应该总是在Controllers文件夹中创建控制器。否则的话,就破坏了ASP.NET MVC的惯例,其他的程序员将会花费更多艰辛的时间来理解你的应用程序。

5.2 创建动作方法

当你创建一个控制器时,你可以选择自动生成Create,Update和Details动作方法(如图3)。如果你选择了这个选项,那么会生成代码2中的控制器类。


Detailed introduction to ASP.NET MVC--controller

代码清单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();
            }
        }
    }
}
Copy after login

这些生成的方法都只是一些存根方法(stub methods)。你必须自己为客户的创建、更新和显示详情添加实际的逻辑。但是,这些存根方法为你提供了一个漂亮的着手点。

5.3 创建一个控制器类

ASP.NET MVC控制器不过是一个类。如果你喜欢,可以无视Visual Studio便利的控制器创建方式,自己手动来创建一个控制器类。按照这些步骤:

右键点击Controllers文件夹,并且选择菜单项Add,New Item,然后选择Class模板。

将新类命名为PersonController.cs,然后点击Add按钮。

修改产生的类文件,让这个类继承自System.Web.Mvc.Controller基类(见代码清单3)。

Detailed introduction to ASP.NET MVC--controller

代码清单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!";
        }
    }
}
Copy after login

代码清单3中的控制器类公布了一个叫做Index()的动作,它返回字符串“Hello World!”。你可以通过运行应用程序,并且请求像下面这样的URL来调用这个控制器动作:

localhost:40071/Person
Copy after login

NOTE:ASP.NET 开发服务器使用一个随机的端口号(例如,40071)。当输入URL来调用控制器时,你需要提供正确的端口号。你可以通过将鼠标悬停在ASP.NET开发服务器的图标上来获得端口号,该图标位于Windows Notification Area(Windows通知区域,屏幕的右下角)。

6. 创建自定义动作

本篇教程的目的是解释如何创建一个新的控制器动作。你会学习到控制器动作的要求。你还会学习如何来阻止将方法公布为控制器动作。

6.1 添加动作到控制器

你可以通过在控制器中添加一个新的方法,将新的动作添加到控制器中。举个例子,代码清单1中的控制器包含了一个叫做Index()和一个叫做SayHello()的动作。这两个方法都公布为了动作。

代码清单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!";
        }
    
    }
}
Copy after login

为了将方法作为一个动作公布给全世界,方法必须满足特定的要求:

方法必须是公共的。

方法不能是静态方法。

方法不能使扩展方法。

方法不能是构造函数,访问器,或者设置器。

方法不能拥有开放泛型类型(open generic types)。

方法不能使控制器基类中的方法。

方法不能含有ref或者out参数。

6.2 阻止公共方法被调用

如果你需要在控制器中创建一个公共方法,但是你不想将这个方法发布为控制器动作,那么你可以通过使用[NonAction]特性来阻止该方法被外界调用。举个例子,代码清单2中的控制器含有一个叫做CompanySecrets()的公共方法,它使用[NonAction]特性进行了修饰。

代码清单2 - Controller\WorkController.cs

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
    public class WorkController : Controller
    {
        [NonAction]
        public string CompanySecrets()
        {
            return "This information is secret.";
        }
    }
}
Copy after login

如果你试图通过在浏览器地址栏输入/Work/CompanySecrets来调用CompanySecrets()控制器动作,那么你会获得图5所示的错误消息:

Detailed introduction to ASP.NET MVC--controller

【相关推荐】

1. 什么是ASP.NET MVC ?总结ASP.NET MVC

2. 深入了解ASP.NET MVC与WebForm的区别

3. 详细介绍ASP.NET MVC--视图

4. 详细介绍ASP.NET MVC--路由

5. 通过asp.net mvc开发微信自定义菜单编辑工具的代码示例

The above is the detailed content of Detailed introduction to ASP.NET MVC--controller. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!