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中描述一些常用的上下文对象。

Table 12-1. Commonly UsedContext Objects
表12-1. 常用的上下文对象

Property
属性

Type
类型

Description
描述

Request.QueryString

NameValueCollection

GET variables sent with this request
用这个请求发送的GET变量

Request.Form

NameValueCollection

POST variables sent with this request
用这个请求发送的POST变量

Request.Cookies

HttpCookieCollection

Cookies sent by the browser with this request
浏览器用这个请求发送的Cookies

Request.HttpMethod

string

The HTTP method (verb, such as GET or POST) used for this request
用于这个请求的HTTP方法(动词,如GET或POST)

Request.Headers

NameValueCollection

The full set of HTTP headers sent with this request
用这个请求发送的整个HTTP头

Request.Url

Uri

The URL requested
所请求的URL

Request.UserHostAddress

string

The IP address of the user making this request
发送请求的用户的IP地址

RouteData.Route

RouteBase

The chosen RouteTable.Routes entry for this request
为这个请求所选择的RouteTable.Routes条目

RouteData.Values

RouteValueDictionary

Active route parameters (either extracted from the URL or default values)
当前路由的参数(或是从URL提取的,或是默认值)

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 ... }

posted on 2012-06-13 20:57  lucky.net  阅读(140)  评论(0编辑  收藏  举报

导航

Copyright luckynet 2013