Επεξεργασία

Κοινή χρήση μέσω


ObjectDataSource.UpdateMethod Property

Definition

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

Property Value

A string that represents the name of the method or function that the ObjectDataSource uses to update data. The default is an empty string.

Examples

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.

The first example shows a Web page that contains two ObjectDataSource controls, a DropDownList control, and a DetailsView control. The first ObjectDataSource control and the DropDownList control are used to retrieve and display employee names from the database. 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>

The second example shows handlers for the Selected and Updating events. 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. The Updating event handler deserializes the object in view state that contains the original data for the data record that is being updated. 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

The third example shows the data access class that interacts with the Northwind database. The class uses LINQ to query and update the Employees table. The example requires a LINQ to SQL class that represents the Northwind database and Employees table. 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

Remarks

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.

The UpdateMethod property delegates to the UpdateMethod property of the ObjectDataSourceView object that is associated with the ObjectDataSource control.

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

The method that is identified by the UpdateMethod property can be an instance method or a static (Shared in Visual Basic) method. 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. 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. You can also handle the ObjectDisposing event that is raised after the method that is specified by the UpdateMethod property is called. If the business object implements the IDisposable interface, the Dispose method is called before the object is destroyed. 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

Parameters are added to the UpdateParameters collection from three sources:

  • From the data-bound control, at run time.

  • From the UpdateParameters element, declaratively.

  • From the Updating event handler, programmatically.

First, any parameters that are generated from data-bound controls are added to the UpdateParameters collection. 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. The exact name of the parameter depends on the OldValuesParameterFormatString property. The data type of these parameters is string. Next, the parameters that are listed in the UpdateParameters element are added. 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. 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.

Important

You should validate any parameter value that you receive from the client. The runtime simply substitutes the parameter value into the UpdateMethod property.

Method Resolution

When 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. (For more information, see the preceding section.) The ObjectDataSource control then attempts to find a method to call. First, it looks for one or more methods with the name that is specified in the UpdateMethod property. If no match is found, an InvalidOperationException exception is thrown. If a match is found, it then looks for matching parameter names. For example, suppose a type that is specified by the TypeName property has two methods named UpdateARecord. One UpdateARecord has one parameter, ID, and the other UpdateARecord has two parameters, Name and Number. If 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.

If the DataObjectTypeName property is set, the method is resolved in a different way. The 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.

Applies to

See also