ObjectDataSource.UpdateMethod ObjectDataSource.UpdateMethod ObjectDataSource.UpdateMethod ObjectDataSource.UpdateMethod Property

定义

获取或设置由 ObjectDataSource 控件调用以更新数据的方法或函数的名称。Gets or sets the name of the method or function that the ObjectDataSource control invokes to update data.

public:
 property System::String ^ UpdateMethod { System::String ^ get(); void set(System::String ^ value); };
public string UpdateMethod { get; set; }
member this.UpdateMethod : string with get, set
Public Property UpdateMethod As String

属性值

表示 ObjectDataSource 用于更新数据的方法或函数的名称的字符串。A string that represents the name of the method or function that the ObjectDataSource uses to update data. 默认值为一个空字符串。The default is an empty string.

示例

以下三个示例演示了一个网页、一个代码隐藏页类和一个数据访问类, 使用户能够在 Northwind 数据库中检索和更新 Employees 表中的记录。The following three examples show a Web page, a code-behind page class, and a data-access class that enable a user to retrieve and update records in the Employees table in the Northwind database.

第一个示例显示一个网页, 其中包含两ObjectDataSource个控件DropDownList : 控件和一个DetailsView控件。The first example shows a Web page that contains two ObjectDataSource controls, a DropDownList control, and a DetailsView control. 第一个ObjectDataSource控件DropDownList和控件用于检索和显示数据库中的雇员姓名。The first ObjectDataSource control and the DropDownList control are used to retrieve and display employee names from the database. 第二ObjectDataSource个控件DetailsView和控件用于从用户选择的员工记录中检索、显示和修改数据。The second ObjectDataSource control and the DetailsView control are used to retrieve, display, and modify the data from the employee record that is selected by the user.

<form id="Form1" method="post" runat="server">

    <asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />

    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>

    <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      UpdateMethod="UpdateEmployeeAddress"
      OnUpdating="EmployeeUpdating"
      OnSelected="EmployeeSelected"
      TypeName="Samples.AspNet.CS.EmployeeLogic" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false"
        AutoGenerateEditButton="true">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
   
</form>
<form id="form1" runat="server">

    <asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />

    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>

    <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      UpdateMethod="UpdateEmployeeAddress"
      OnUpdating="EmployeeUpdating"
      OnSelected="EmployeeSelected"
      TypeName="Samples.AspNet.CS.EmployeeLogic" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false"
        AutoGenerateEditButton="true">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
   
</form>

第二个示例显示了SelectedUpdating事件的处理程序。The second example shows handlers for the Selected and Updating events. Selected事件处理程序将序列化包含从 Employee 表中检索到的数据的对象。The Selected event handler serializes the object that contains data that was retrieved from the Employee table. 序列化的对象存储在视图状态中。The serialized object is stored in view state. Updating事件处理程序在视图状态中对对象进行反序列化, 其中包含要更新的数据记录的原始数据。The Updating event handler deserializes the object in view state that contains the original data for the data record that is being updated. 包含原始数据的对象将作为参数传递给 Update 方法。The object that contains the original data is passed as a parameter to the Update method. 必须将原始数据传递到数据库, 以便可以使用它来检查数据是否已被其他进程修改。The original data must be passed to the database so that it can be used to check whether the data has been modified by another process.

public void EmployeeUpdating(object source, ObjectDataSourceMethodEventArgs e)
{
    DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));

    String xmlData = ViewState["OriginalEmployee"].ToString();
    XmlReader reader = XmlReader.Create(new StringReader(xmlData));
    Employee originalEmployee = (Employee)dcs.ReadObject(reader);
    reader.Close();

    e.InputParameters.Add("originalEmployee", originalEmployee);
}

public void EmployeeSelected(object source, ObjectDataSourceStatusEventArgs e)
{
    if (e.ReturnValue != null)
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);
        dcs.WriteObject(writer, e.ReturnValue);
        writer.Close();

        ViewState["OriginalEmployee"] = sb.ToString();
    }
}
Public Sub EmployeeUpdating(ByVal source As Object, ByVal e As ObjectDataSourceMethodEventArgs)
    Dim dcs As New DataContractSerializer(GetType(Employee))
    Dim xmlData As String
    Dim reader As XmlReader
    Dim originalEmployee As Employee

    xmlData = ViewState("OriginalEmployee").ToString()
    reader = XmlReader.Create(New StringReader(xmlData))
    originalEmployee = CType(dcs.ReadObject(reader), Employee)
    reader.Close()

    e.InputParameters.Add("originalEmployee", originalEmployee)
End Sub

Public Sub EmployeeSelected(ByVal source As Object, ByVal e As ObjectDataSourceStatusEventArgs)
    If e.ReturnValue IsNot Nothing Then
        Dim dcs As New DataContractSerializer(GetType(Employee))
        Dim sb As New StringBuilder()
        Dim writer As XmlWriter
        writer = XmlWriter.Create(sb)
        dcs.WriteObject(writer, e.ReturnValue)
        writer.Close()

        ViewState("OriginalEmployee") = sb.ToString()
    End If
End Sub

第三个示例显示与 Northwind 数据库交互的数据访问类。The third example shows the data access class that interacts with the Northwind database. 类使用 LINQ 来查询和更新 Employees 表。The class uses LINQ to query and update the Employees table. 该示例需要一个 LINQ to SQL 类, 该类表示 Northwind 数据库和 Employees 表。The example requires a LINQ to SQL class that represents the Northwind database and Employees table. 有关详细信息,请参阅如何:在 Web 项目中创建 LINQ to SQL 类。For more information, see How to: Create LINQ to SQL Classes in a Web Project.

public class EmployeeLogic
{
    public static Array GetFullNamesAndIDs()
    {
        NorthwindDataContext ndc = new NorthwindDataContext();

        var employeeQuery =
            from e in ndc.Employees
            orderby e.LastName
            select new { FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID };

        return employeeQuery.ToArray();
    }

    public static Employee GetEmployee(int empID)
    {
        if (empID < 0)
        {
            return null;
        }
        else
        {
            NorthwindDataContext ndc = new NorthwindDataContext();
            var employeeQuery =
                from e in ndc.Employees
                where e.EmployeeID == empID
                select e;

            return employeeQuery.Single();
        }
    }
 
    public static void UpdateEmployeeAddress(Employee originalEmployee, string address, string city, string postalcode)
    {
        NorthwindDataContext ndc = new NorthwindDataContext();
        ndc.Employees.Attach(originalEmployee, false);
        originalEmployee.Address = address;
        originalEmployee.City = city;
        originalEmployee.PostalCode = postalcode;
        ndc.SubmitChanges();
    }
}
Public Class EmployeeLogic
    Public Shared Function GetFullNamesAndIDs() As Array
        Dim ndc As New NorthwindDataContext()

        Dim employeeQuery = _
            From e In ndc.Employees _
            Order By e.LastName _
            Select FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID

        Return employeeQuery.ToArray()
    End Function

    Public Shared Function GetEmployee(ByVal empID As Integer) As Employee

        If (empID < 0) Then
            Return Nothing
        Else
            Dim ndc As New NorthwindDataContext()
            Dim employeeQuery = _
                From e In ndc.Employees _
                Where e.EmployeeID = empID _
                Select e

            Return employeeQuery.Single()
        End If
    End Function

    Public Shared Sub UpdateEmployeeAddress(ByVal originalEmployee As Employee, ByVal address As String, ByVal city As String, ByVal postalcode As String)

        Dim ndc As New NorthwindDataContext()
        ndc.Employees.Attach(originalEmployee, False)
        originalEmployee.Address = address
        originalEmployee.City = city
        originalEmployee.PostalCode = postalcode
        ndc.SubmitChanges()
    End Sub
End Class

注解

ObjectDataSource控件假设UpdateMethod由属性标识的方法每次执行一个更新, 而不是在批处理中执行更新。The ObjectDataSource control assumes that the method that is identified by the UpdateMethod property performs updates one at a time, rather than in a batch.

属性委托ObjectDataSourceView UpdateMethod给与ObjectDataSource控件相关联的对象的属性。 UpdateMethodThe UpdateMethod property delegates to the UpdateMethod property of the ObjectDataSourceView object that is associated with the ObjectDataSource control.

请确保为ObjectDataSource UpdateParameters集合中的控件配置的参数名称与 select 方法返回的列名称相匹配。Make sure that the parameter names configured for the ObjectDataSource control in the UpdateParameters collection match the column names that are returned by the select method.

对象生存期Object Lifetime

UpdateMethod属性标识的方法可以是实例方法, static也可以是 (Shared在 Visual Basic) 方法。The method that is identified by the UpdateMethod property can be an instance method or a static (Shared in Visual Basic) method. 如果它是实例方法, 则每次调用由UpdateMethod属性指定的方法时都会创建并销毁业务对象。If it is an instance method, the business object is created and destroyed each time the method that is specified by the UpdateMethod property is called. 在调用由ObjectCreated ObjectCreating 属性指定的方法之前,您可以处理和事件来UpdateMethod处理业务对象。You can handle the ObjectCreated and ObjectCreating events to work with the business object before the method that is specified by the UpdateMethod property is called. 你还可以处理在ObjectDisposing调用UpdateMethod由属性指定的方法之后引发的事件。You can also handle the ObjectDisposing event that is raised after the method that is specified by the UpdateMethod property is called. 如果业务对象实现IDisposable接口Dispose , 则在销毁对象之前调用方法。If the business object implements the IDisposable interface, the Dispose method is called before the object is destroyed. 如果该方法为static (Shared在 Visual Basic 中), 则永远不会创建业务对象, 也不ObjectCreatedObjectCreating处理、 ObjectDisposing和事件。If the method is static (Shared in Visual Basic), the business object is never created and you cannot handle the ObjectCreated, ObjectCreating, and ObjectDisposing events.

参数合并Parameter Merging

将参数添加到集合UpdateParameters中的三个源:Parameters are added to the UpdateParameters collection from three sources:

  • 在运行时从数据绑定控件。From the data-bound control, at run time.

  • UpdateParameters从元素中以声明方式。From the UpdateParameters element, declaratively.

  • Updating从事件处理程序中以编程方式。From the Updating event handler, programmatically.

首先, 将从数据绑定控件生成的所有参数添加到UpdateParameters集合中。First, any parameters that are generated from data-bound controls are added to the UpdateParameters collection. ObjectDataSource例如, 如果将控件绑定GridView到具有列NameNumber的控件, 则NameNumber的参数将添加到集合中。For example, if the ObjectDataSource control is bound to a GridView control that has the columns Name and Number, the parameters for Name and Number are added to the collection. 参数的确切名称取决于OldValuesParameterFormatString属性。The exact name of the parameter depends on the OldValuesParameterFormatString property. 这些参数的数据类型为stringThe data type of these parameters is string. 接下来, 添加UpdateParameters元素中列出的参数。Next, the parameters that are listed in the UpdateParameters element are added. 如果找到了UpdateParameters元素中与UpdateParameters集合中已有的参数同名的参数, 则会修改现有参数, 使其与UpdateParameters元素中指定的参数匹配。If a parameter in the UpdateParameters element is found with the same name as a parameter that is already in the UpdateParameters collection, the existing parameter is modified to match the parameter that is specified in the UpdateParameters element. 通常, 这用于修改参数中数据的类型。Typically, this is used to modify the type of the data in the parameter. 最后, 你可以通过编程方式在运行Updating Update方法之前, 在事件中添加和移除参数。Finally, you can programmatically add and remove parameters in the Updating event, which occurs before the Update method is run. 合并参数后, 解析方法。The method is resolved after the parameters are merged. 下一节将讨论方法解析。Method resolution is discussed in the next section.

重要

你应验证从客户端接收的任何参数值。You should validate any parameter value that you receive from the client. 运行时只需将参数值替换为UpdateMethod属性。The runtime simply substitutes the parameter value into the UpdateMethod property.

方法解析Method Resolution

调用方法时, 数据绑定控件中的数据字段、在UpdateParameters元素中以声明方式创建的参数以及在Updating事件处理程序中添加的参数都将合并。 UpdateWhen the Update method is called, the data fields from the data-bound control, the parameters that were created declaratively in the UpdateParameters element, and the parameters that were added in the Updating event handler are all merged. (有关详细信息, 请参阅前面的部分。)然后ObjectDataSource , 控件尝试查找要调用的方法。(For more information, see the preceding section.) The ObjectDataSource control then attempts to find a method to call. 首先, 它会查找一个或多个具有在UpdateMethod属性中指定的名称的方法。First, it looks for one or more methods with the name that is specified in the UpdateMethod property. 如果未找到匹配项, InvalidOperationException则会引发异常。If no match is found, an InvalidOperationException exception is thrown. 如果找到匹配项, 则它将查找匹配的参数名称。If a match is found, it then looks for matching parameter names. 例如, 假设TypeName属性指定的类型有两个名为UpdateARecord的方法。For example, suppose a type that is specified by the TypeName property has two methods named UpdateARecord. 一个UpdateARecord UpdateARecord 参数为,另Name一个参数Number具有两个参数: 和。 IDOne UpdateARecord has one parameter, ID, and the other UpdateARecord has two parameters, Name and Number. 如果集合仅包含一个名为ID的参数, UpdateARecord则将调用只ID包含参数的方法。 UpdateParametersIf the UpdateParameters collection has only one parameter named ID, the UpdateARecord method with just the ID parameter is called. 解析方法时未检查参数类型。The type of the parameter is not checked in resolving the methods. 参数的顺序并不重要。The order of the parameters does not matter.

如果设置了属性, 则会以不同的方式解析方法。 DataObjectTypeNameIf the DataObjectTypeName property is set, the method is resolved in a different way. 查找具有在属性中指定的名称的方法, 该属性采用在DataObjectTypeName属性中指定的类型的一个参数。 UpdateMethod ObjectDataSourceThe ObjectDataSource looks for a method with the name that is specified in the UpdateMethod property that takes one parameter of the type that is specified in the DataObjectTypeName property. 在这种情况下, 参数名称并不重要。In this case, the name of the parameter does not matter.

适用于

另请参阅