ObjectDataSource.UpdateMethod Свойство
Определение
Возвращает или задает имя метода или функции, вызываемого элемента управления 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.
Примеры
В следующих трех примерах показана веб-страница, класс страницы кода программной части и класс доступа к данным, позволяющие пользователю извлекать и обновлять записи в таблице Employees в базе данных Northwind.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>
Во втором примере показаны обработчики для Selected событий Updating и.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. Дополнительные сведения см. в разделе Практическое руководство. Создание 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
Комментарии
Элемент управления предполагает, что метод, идентифицируемый UpdateMethod свойством, выполняет обновление по одному за раз, а не в пакете. ObjectDataSourceThe ObjectDataSource control assumes that the method that is identified by the UpdateMethod property performs updates one at a time, rather than in a batch.
Свойство делегирует UpdateMethod ObjectDataSource свойство ObjectDataSourceView объекта, связанного с элементом управления. 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), бизнес-объект никогда не создается ObjectCreatedи вы не можете управлять событиями, ObjectDisposing ObjectCreatingи.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 theUpdateParameters
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 к элементу управления со столбцами Name
и Number
, параметры для Name
и Number
добавляются в коллекцию.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. Эти параметры имеют string
тип данных.The 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
имеет один ID
параметр,, а другой UpdateARecord
имеет два параметра: Name
и Number
.One 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.
DataObjectTypeName Если свойство задано, метод разрешается другим способом.If the DataObjectTypeName property is set, the method is resolved in a different way. Выполняет поиск метода с именем, указанным UpdateMethod в свойстве, которое принимает один параметр типа DataObjectTypeName , указанного в свойстве. 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.
Применяется к
Дополнительно
- UpdateParameters
- Update()
- Элементы управления веб-сервером с источником данныхData Source Web Server Controls
- Общие сведения об элементе управления ObjectDataSourceObjectDataSource Control Overview
- Создание исходного объекта элемента управления ObjectDataSourceCreating an ObjectDataSource Control Source Object
- Использование Entity Framework и элемента управления ObjectDataSourceUsing the Entity Framework and the ObjectDataSource Control