QueryStringParameter 类

定义

将 HTTP 请求查询字符串字段的值绑定到参数对象。Binds the value of an HTTP request query-string field to a parameter object.

public ref class QueryStringParameter : System::Web::UI::WebControls::Parameter
public class QueryStringParameter : System.Web.UI.WebControls.Parameter
type QueryStringParameter = class
    inherit Parameter
Public Class QueryStringParameter
Inherits Parameter
继承
QueryStringParameter

示例

下面的示例演示如何创建QueryStringParameterGridView控件中显示数据时用作筛选器的对象。The following example shows how to create a QueryStringParameter object to use as a filter when you display data in a GridView control. QueryStringParameter对象添加AccessDataSource到控件的FilterParameters集合。You add the QueryStringParameter object to the AccessDataSource control's FilterParameters collection. 参数对象将名country为的查询字符串字段的值绑定到其FilterExpression字符串。The parameter object binds the value of the query-string field named country to its FilterExpression string. 由于没有DefaultValue为该参数指定任何属性,因此,如果没有country与查询字符串一起传递名为的AccessDataSource字段,则NullReferenceException控件将引发异常。Because no DefaultValue property is specified for the parameter, if no field named country is passed with the query string, the AccessDataSource control throws a NullReferenceException exception. 如果传递了名country为的字段,但没有值, GridView则控件不显示任何数据。If a field named country is passed but has no value, the GridView control displays no data.

<%@ Page language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="Form1" method="post" runat="server">

      <!-- Use a Query String with country=USA -->
      <asp:gridview
        id ="GridView1"
        runat="server"
        datasourceid="MyAccessDataSource" />

<!-- Security Note: The AccessDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client. -->

      <asp:accessdatasource
        id="MyAccessDataSource"
        runat="server"
        datafile="Northwind.mdb"
        selectcommand="SELECT EmployeeID, LastName, Address, PostalCode, Country FROM Employees"
        filterexpression="Country = '{0}'">
        <filterparameters>
          <asp:querystringparameter name="country" type="String" querystringfield="country" />
        </filterparameters>
      </asp:accessdatasource>
    </form>
  </body>
</html>
<%@ Page language="VB"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="Form1" method="post" runat="server">

      <!-- Use a Query String with country=USA -->
      <asp:gridview
        id ="GridView1"
        runat="server"
        datasourceid="MyAccessDataSource" />

<!-- Security Note: The AccessDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client. -->

      <asp:accessdatasource
        id="MyAccessDataSource"
        runat="server"
        datafile="Northwind.mdb"
        selectcommand="SELECT EmployeeID, LastName, Address, PostalCode, Country FROM Employees"
        filterexpression="Country = '{0}'">
        <filterparameters>
          <asp:querystringparameter name="country" type="String" querystringfield="country" />
        </filterparameters>
      </asp:accessdatasource>

    </form>
  </body>
</html>

下面的示例演示如何通过使用参数QueryStringParameter化 SQL 查询创建对象以显示 Access 数据库中的数据。The following example shows how to create a QueryStringParameter object to display data from an Access database by using a parameterized SQL query. 对象检索随后显示GridView在控件中的记录。 AccessDataSourceThe AccessDataSource object retrieves records that are then displayed in a GridView control. GridView控件也可编辑,并允许用户更新 Northwind 商贸 orders 表中订单的状态。The GridView control is also editable, and lets users update the status of orders in the Northwind Traders Orders table.

<%@Page  Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
  // This method is an example of batch updating using a
  // data source control. The method iterates through the rows
  // of the GridView, extracts each CheckBox from the row and, if
  // the CheckBox is checked, updates data by calling the Update
  // method of the data source control, adding required parameters
  // to the UpdateParameters collection.
  CheckBox cb;
  foreach(GridViewRow row in this.GridView1.Rows) {
    cb = (CheckBox) row.Cells[0].Controls[1];
    if(cb.Checked) {
      string oid = (string) row.Cells[1].Text;
      MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
      MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
      MyAccessDataSource.Update();
      MyAccessDataSource.UpdateParameters.Clear();
    }
  }
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->

      <asp:SqlDataSource
        id="MyAccessDataSource"
        runat="server"
        ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
        ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
        SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
        UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
        <SelectParameters>
          <asp:QueryStringParameter Name="empId" QueryStringField="empId" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:GridView
        id ="GridView1"
        runat="server"
        DataSourceID="MyAccessDataSource"
        AllowPaging="True"
        PageSize="10"
        AutoGenerateColumns="False">
          <columns>
            <asp:TemplateField HeaderText="">
              <ItemTemplate>
                <asp:CheckBox runat="server" />
              </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Order" DataField="OrderID" />
            <asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
            <asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
            <asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
          </columns>
      </asp:GridView>

      <asp:Button
        id="Button1"
        runat="server"
        Text="Update the Selected Records As Shipped"
        OnClick="UpdateRecords" />

      <asp:Label id="Label1" runat="server" />

    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)

  ' This method is an example of batch updating using a
  ' data source control. The method iterates through the rows
  ' of the GridView, extracts each CheckBox from the row and, if
  ' the CheckBox is checked, updates data by calling the Update
  ' method of the data source control, adding required parameters
  ' to the UpdateParameters collection.

  Dim cb As CheckBox
  Dim row As GridViewRow

  For Each row In GridView1.Rows

    cb = CType(row.Cells(0).Controls(1), CheckBox)
    If cb.Checked Then

      Dim oid As String
      oid = CType(row.Cells(1).Text, String)

      Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
      MyAccessDataSource.UpdateParameters.Add(param1)

      Dim param2 As New Parameter("orderid", TypeCode.String, oid)
      MyAccessDataSource.UpdateParameters.Add(param2)

      MyAccessDataSource.Update()
      MyAccessDataSource.UpdateParameters.Clear()
    End If
  Next
End Sub ' UpdateRecords
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->

      <asp:SqlDataSource
        id="MyAccessDataSource"
        runat="server"
        ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
        ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
        SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
        UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
        <SelectParameters>
          <asp:QueryStringParameter Name="empId" QueryStringField="empId" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:GridView
        id ="GridView1"
        runat="server"
        DataSourceID="MyAccessDataSource"
        AllowPaging="True"
        PageSize="10"
        AutoGenerateColumns="False">
          <columns>
            <asp:TemplateField HeaderText="">
              <ItemTemplate>
                <asp:CheckBox runat="server" />
              </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Order" DataField="OrderID" />
            <asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
            <asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
            <asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
          </columns>
      </asp:GridView>

      <asp:Button
        id="Button1"
        runat="server"
        Text="Update the Selected Records As Shipped"
        OnClick="UpdateRecords" />

      <asp:Label id="Label1" runat="server" />

    </form>
  </body>
</html>

注解

可以使用QueryStringParameter类将作为 HTTP 请求查询字符串的一部分传递的字段的值绑定到参数化的查询或命令中使用的参数。You can use the QueryStringParameter class to bind the value of a field that is passed as part of an HTTP request query string to a parameter that is used in a parameterized query or command. 该字段从QueryString集合中检索。The field is retrieved from the QueryString collection.

如果引用了QueryStringParameter对象,但未传递相应的查询字符串名称/值对,则将数据绑定到参数的控件可能会引发异常。Controls that bind data to the parameter might throw an exception if a QueryStringParameter object is referenced, but no corresponding query-string name/value pair is passed. 同样,如果传递的查询字符串字段名称没有相应的值,则它们可能不显示任何数据。Similarly, they might display no data if the query-string field name is passed without a corresponding value. 若要避免出现这种情况DefaultValue ,请在适当的位置设置属性。To avoid these situations, set the DefaultValue property where appropriate.

QueryStringParameterQueryStringField提供属性,该属性标识要绑定到的查询字符串值的名称。The QueryStringParameter class provides the QueryStringField property, which identifies the name of the query string value to bind to. 它还提供从Parameter类继承的属性。It also provides the properties that are inherited from the Parameter class.

重要

QueryStringParameter类不会验证传递的值; 它提供原始值。The QueryStringParameter class does not validate the value that is passed; it provides the raw value. 但是,可以在数据源控件中验证QueryStringParameter对象的值。However, you can validate the value of a QueryStringParameter object in a data source control. 为此,请Selecting处理数据源控件的、 Deleting UpdatingInserting或事件,并在事件处理程序中检查参数值。To do so, handle the Selecting, Updating, Inserting, or Deleting event of the data source control and check the parameter value in the event handler. 如果参数的值未通过验证测试,则可以通过将关联Cancel CancelEventArgs类的属性设置为来true取消数据操作。If the value of the parameter does not pass the validation tests, you can cancel the data operation by setting the Cancel property of the associated CancelEventArgs class to true.

构造函数

QueryStringParameter()

初始化 QueryStringParameter 类的未命名新实例。Initializes a new unnamed instance of the QueryStringParameter class.

QueryStringParameter(QueryStringParameter)

使用 original 参数指定的实例的值初始化 QueryStringParameter 类的新实例。Initializes a new instance of the QueryStringParameter class, using the values of the instance that is specified by the original parameter.

QueryStringParameter(String, DbType, String)

使用指定的查询字符串字段和参数的数据类型,初始化 QueryStringParameter 类的新命名实例。Initializes a new named instance of the QueryStringParameter class, using the specified query-string field and the data type of the parameter.

QueryStringParameter(String, String)

使用指定的字符串来标识要绑定到的查询字符串字段,初始化 QueryStringParameter 类的新命名实例。Initializes a new named instance of the QueryStringParameter class, using the specified string to identify which query-string field to bind to.

QueryStringParameter(String, TypeCode, String)

使用指定的字符串来标识要绑定到的查询字符串字段,初始化 QueryStringParameter 类的新强类型命名实例。Initializes a new named and strongly typed instance of the QueryStringParameter class, using the specified string to identify which query-string field to bind to.

属性

ConvertEmptyStringToNull

获取或设置一个值,该值指示在 Parameter 对象绑定到的值为 Empty 时是否应将其转换为 nullGets or sets a value indicating whether the value that the Parameter object is bound to should be converted to null if it is Empty.

(继承自 Parameter)
DbType

获取或设置参数的数据库类型。Gets or sets the database type of the parameter.

(继承自 Parameter)
DefaultValue

指定参数的默认值(如果调用 Evaluate(HttpContext, Control) 方法时参数绑定到的值未被初始化)。Specifies a default value for the parameter, should the value that the parameter is bound to be uninitialized when the Evaluate(HttpContext, Control) method is called.

(继承自 Parameter)
Direction

指示 Parameter 对象是否用于将值绑定到控件,或者是否可以使用控件更改值。Indicates whether the Parameter object is used to bind a value to a control, or the control can be used to change the value.

(继承自 Parameter)
IsTrackingViewState

获取一个值,该值指示 Parameter 对象是否保存对其视图状态的更改。Gets a value indicating whether the Parameter object is saving changes to its view state.

(继承自 Parameter)
Name

获取或设置参数的名称。Gets or sets the name of the parameter.

(继承自 Parameter)
QueryStringField

获取或设置参数所绑定的查询字符串字段的名称。Gets or sets the name of the query-string field that the parameter binds to.

Size

获取或设置参数的大小。Gets or sets the size of the parameter.

(继承自 Parameter)
Type

获取或设置参数类型。Gets or sets the type of the parameter.

(继承自 Parameter)
ValidateInput

获取或设置是否验证查询字符串参数的值。Gets or sets whether the value of the query string parameter is being validated or not.

ViewState

获取状态信息的字典,这些信息使您可以在同一页的多个请求间保存和还原 Parameter 对象的视图状态。Gets a dictionary of state information that allows you to save and restore the view state of a Parameter object across multiple requests for the same page.

(继承自 Parameter)

方法

Clone()

返回当前 QueryStringParameter 实例的副本。Returns a duplicate of the current QueryStringParameter instance.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Evaluate(HttpContext, Control)

更新并返回 QueryStringParameter 对象的值。Updates and returns the value of the QueryStringParameter object.

GetDatabaseType()

获取与当前 DbType 实例的 CLR 类型等效的 Parameter 值。Gets the DbType value that is equivalent to the CLR type of the current Parameter instance.

(继承自 Parameter)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
LoadViewState(Object)

将数据源视图还原为保存过的前一视图状态。Restores the data source view's previously saved view state.

(继承自 Parameter)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OnParameterChanged()

调用包含 OnParametersChanged(EventArgs) 对象的 ParameterCollection 集合的 Parameter 方法。Calls the OnParametersChanged(EventArgs) method of the ParameterCollection collection that contains the Parameter object.

(继承自 Parameter)
SaveViewState()

自页回发到服务器开始,将更改保存到 Parameter 对象的视图状态。Saves the changes to the Parameter object's view state since the time the page was posted back to the server.

(继承自 Parameter)
SetDirty()

标记 Parameter 对象,以便在视图状态中记录其状态。Marks the Parameter object so its state will be recorded in view state.

(继承自 Parameter)
ToString()

将此实例的值转换为其等效的字符串表示形式。Converts the value of this instance to its equivalent string representation.

(继承自 Parameter)
TrackViewState()

使 Parameter 对象跟踪其视图状态更改,以便这些更改可以存储在控件的 ViewState 对象中并在同一页面的不同请求间保留。Causes the Parameter object to track changes to its view state so they can be stored in the control's ViewState object and persisted across requests for the same page.

(继承自 Parameter)

显式界面实现

ICloneable.Clone()

返回当前 Parameter 实例的副本。Returns a duplicate of the current Parameter instance.

(继承自 Parameter)
IStateManager.IsTrackingViewState

获取一个值,该值指示 Parameter 对象是否保存对其视图状态的更改。Gets a value indicating whether the Parameter object is saving changes to its view state.

(继承自 Parameter)
IStateManager.LoadViewState(Object)

将数据源视图还原为保存过的前一视图状态。Restores the data source view's previously saved view state.

(继承自 Parameter)
IStateManager.SaveViewState()

自页回发到服务器开始,将更改保存到 Parameter 对象的视图状态。Saves the changes to the Parameter object's view state since the time the page was posted back to the server.

(继承自 Parameter)
IStateManager.TrackViewState()

使 Parameter 对象跟踪其视图状态更改,以便这些更改可以存储在控件的 ViewState 对象中并在同一页面的不同请求间保留。Causes the Parameter object to track changes to its view state so they can be stored in the control's ViewState object and persisted across requests for the same page.

(继承自 Parameter)

适用于

另请参阅