12.2 接收输入 — 精通 MVC 3 框架
Receiving Input
接收输入
Controllers frequentlyneed to access incoming data, such as query string values, form values, andparameters parsed from the incoming URL by the routing system. There are threemain ways to access that data:
控制器经常需要访问输入数据,如查询字串值、表单值、以及通过路由系统从输入URL解析所得到的参数。有三个主要的办法来访问这些数据:
- Extract it from a set of context objects.
通过一组上下文对象进行提取。 - Have the data passed as parameters to your action method.
拥有作为参数被传递到动作方法的数据。 - Explicitly invoke the framework’s model binding feature.
明确地调用框架的模型绑定特性。
Here, we’ll look at theapproaches for getting input for your action methods, focusing on using contextobjects and action method parameters. In Chapter 17, we’ll cover model bindingin depth.
以下,我们将考查为动作方法获取输入的途径,关注于使用上下文对象以及动作方法参数。在第17章中,我们将深度涉及模型绑定。
Getting Data from Context Objects
通过上下文获取数据
The most direct way to gethold of data is to fetch it yourself. When you create a controller by derivingfrom the Controller base class, you get access to a set of convenienceproperties to access information about the request. These properties includeRequest, Response, RouteData, HttpContext, and Server. Each providesinformation about a different aspect of the request. We refer to these asconvenience properties, because they each retrieve different types of data fromthe request’s ControllerContext instance (which can be accessed through theController.ControllerContext property). We have described some of the mostcommonly used context objects in Table 12-1.
抓取数据最直接的办法是你自己去拿。当你的控制器是通过Controller基类派生而来的时候,你便得到了一组便利属性来访问与请求相关的信息。这些便利属性包括Request、Response、RouteData、HttpContext、以及Server。每一个都包含了请求的不同方面的信息。我们把这些称为便利属性,是因为它们每一个都从请求的ControllerContext实例(可以通过Controller.ControllerContext属性对它进行访问)接受了不同类型的数据。我们在表12-1中描述了一些最常用的上下文对象。
Property |
Type |
Description |
Request.QueryString |
NameValueCollection |
GET variables sent with this request |
Request.Form |
NameValueCollection |
POST variables sent with this request |
Request.Cookies |
HttpCookieCollection |
Cookies sent by the browser with this request |
Request.HttpMethod |
string |
The HTTP method (verb, such as GET or POST) used for this request |
Request.Headers |
NameValueCollection |
The full set of HTTP headers sent with this request |
Request.Url |
Uri |
The URL requested |
Request.UserHostAddress |
string |
|
RouteData.Route |
RouteBase |
The chosen RouteTable.Routes entry for this request |
RouteData.Values |
RouteValueDictionary |
Active route parameters (either extracted from the URL or default values) |
HttpContext.Application |
HttpApplicationStateBase |
Application state store |
HttpContext.Cache |
Cache |
Application cache store |
HttpContext.Items |
IDictionary |
State store for the current request |
HttpContext.Session |
HttpSessionStateBase |
State store for the visitor’s session |
User |
IPrincipal |
Authentication information about the logged-in user |
TempData |
TempDataDictionary |
Temporary data items stored for the current user |
An action method can useany of these context objects to get information about the request, as Listing12-5 demonstrates.
在一个动作方法中,可以用这些上下文对象的任意一个来获取与请求相关的信息,如清单12-5所示(有些未在表12-1中说明,比如Server — 译者注)。
Listing 12-5. An ActionMethod Using Context Objects to Get Information About a Request
清单12-5. 使用上下文对象获取请求相关信息的一个动作方法
publicActionResult RenameProduct() { // Access various properties from contextobjects string userName = User.Identity.Name; string serverName = Server.MachineName; string clientIP = Request.UserHostAddress; DateTime dateStamp = HttpContext.Timestamp; AuditRequest(userName, serverName,clientIP, dateStamp, "Renaming product"); // Retrieve posted data from Request.Form string oldProductName =Request.Form["OldName"]; string newProductName =Request.Form["NewName"]; bool result =AttemptProductRename(oldProductName, newProductName); ViewData["RenameResult"] =result; return View("ProductRenamed"); }
You can explore the vastrange of available request context information using IntelliSense (in an actionmethod, type this. and browse the pop-up), and the Microsoft Developer Network(look up System.Web.Mvc.Controller and its base classes, orSystem.Web.Mvc.ControllerContext).
你可以用智能感应(在一个动作方法中,输入this.,并浏览弹出的内容)、和微软开发者网络(查看System.Web.Mvc.Controller及其基类,或System.Web.Mvc.ControllerContext)来浏览这些大量可用的请求上下文信息。
Using Action Method Parameters
使用动作方法参数
As you’ve seen in previouschapters, action methods can take parameters. This is a neater way to receiveincoming data than extracting it manually from context objects, and it makesyou action methods easier to read. For example, suppose we have an actionmethod that uses context objects like this:
正如在前面一些章节你已经看到的,动作方法可以有参数。这是一种比通过上下文对象提取数据更灵活的接收输入数据的办法,而且这使你的动作方法更易于阅读。例如,假设我们有一个像下面这样使用上下文对象的动作方法:
public ActionResult ShowWeatherForecast(){ stringcity = RouteData.Values["city"]; DateTimeforDate = DateTime.Parse(Request.Form["forDate"]); // ...implement weather forecast here ... }
We can rewrite it to useparameters, like this:
我们可以把它重写成使用参数的形式,像这样:
public ActionResult ShowWeatherForecast(stringcity, DateTime forDate){ // ...implement weather forecast here ... }