Creating a Controller and Action摘录
Creating a Controller (C#)
原文URL:http://www.asp.net/learn/mvc/tutorial-33-cs.aspx
1. Using the Add Controller Menu Option
1.1 The easiest way to create a new controller is to right-click the Controllers folder in the Visual Studio Solution Explorer window and select the Add, Controller menu option (see Figure 1). Selecting this menu option opens the Add Controller dialog (see Figure 2).
Notice that the first part of the controller name is highlighted in the Add Controller dialog. Every controller name must end with the suffix Controller. For example, you can create a controller named ProductController but not a controller named Product.
1.2 When you create a controller, you have the option to generate Create, Update, and Details action methods automatically (see Figure 3). If you select this option then the controller class in Listing 2 is generated.
These generated methods are stub methods. You must add the actual logic for creating, updating, and showing details for a customer yourself. But, the stub methods provide you with a nice starting point.
2. Controller命名注意事项
If you create a controller that is missing the Controller suffix then you won’t be able to invoke the controller. Don’t do this -- I’ve wasted countless hours of my life after making this mistake.
3. Creating a Controller Class
The ASP.NET MVC controller is just a class. If you prefer, you can ignore the convenient Visual Studio controller scaffolding and create a controller class by hand. Follow these steps:
1.Right-click the Controllers folder and select the menu option Add, New Item and select the Class template (see Figure 4).
2.Name the new class PersonController.cs and click the Add button.
3.Modify the resulting class file so that the class inherits from the base System.Web.Mvc.Controller class (see Listing 3).
Creating an Action (C#)
原文URL:http://www.asp.net/learn/mvc/tutorial-34-cs.aspx
1. Adding an Action to a Controller
In order to be exposed to the universe as an action, a method must meet certain requirements:
The method must be public.
The method cannot be a static method.
The method cannot be an extension method.
The method cannot be a constructor, getter, or setter.
The method cannot have open generic types.
The method is not a method of the controller base class.
The method cannot contain ref or out parameters.
2. Preventing a Public Method from Being Invoked
If you need to create a public method in a controller class and you don’t want to expose the method as a controller action then you can prevent the method from being invoked by using the [NonAction] attribute. For example, the controller in Listing 2 contains a public method named CompanySecrets() that is decorated with the [NonAction] attribute.