ObjectDataSource.DataObjectTypeName Свойство
Определение
Возвращает или задает имя класса, используемое элементом управления ObjectDataSource в качестве параметра в операции обновления, вставки или удаления данных вместо передачи отдельных значений из элемента управления с привязкой к данным.Gets or sets the name of a class that the ObjectDataSource control uses for a parameter in an update, insert, or delete data operation, instead of passing individual values from the data-bound control.
public:
property System::String ^ DataObjectTypeName { System::String ^ get(); void set(System::String ^ value); };
public string DataObjectTypeName { get; set; }
member this.DataObjectTypeName : string with get, set
Public Property DataObjectTypeName As String
Значение свойства
Полное или сокращенное имя класса, обозначающее тип объекта, который может использоваться объектом ObjectDataSource в качестве параметра операции Insert(), Update() или Delete().A partially or fully qualified class name that identifies the type of the object that the ObjectDataSource can use as a parameter for an Insert(), Update(), or a Delete() operation. Значение по умолчанию — пустая строка ("").The default is an empty string ("").
Примеры
Раздел содержит два примера кода.The section contains two code examples. В первом примере кода показано, как реализовать тип, объединяющий все значения параметров в один объект с помощью DataObjectTypeName Свойства.The first code example demonstrates how to implement a type that combines all parameter values into one object, using the DataObjectTypeName property. Во втором примере кода показана веб-страница, использующая два класса, которые используются в первом примере кода.The second code example shows the Web page that uses the two classes that are used in the first code example.
В следующем примере кода показано, как реализовать тип, объединяющий все значения параметров в один объект с помощью DataObjectTypeName Свойства.The following code example demonstrates how to implement a type that combines all parameter values into one object, using the DataObjectTypeName property. Метод Select AggregateData
класса возвращает DataTable объект с двумя столбцами с именами Name
и Number
.The select method of the AggregateData
class returns a DataTable object with two columns named Name
and Number
. Аналогичным образом NewData
класс определяет два свойства для чтения и записи, Name
и Number
.Similarly, the NewData
class defines two read/write properties, Name
and Number
. Insert
Метод AggregateData
класса принимает один параметр типа NewData
.The Insert
method of the AggregateData
class takes one parameter of type NewData
. TypeName
Свойство объекта ObjectDataSource имеет значение AggregateData
, а DataObjectTypeName свойство имеет значение NewData
.The TypeName
property of the ObjectDataSource is set to AggregateData
and the DataObjectTypeName property is set to NewData
.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Samples.AspNet.CS
{
/// <summary>
/// Summary description for AggregateData
/// </summary>
public class AggregateData
{
public AggregateData()
{
}
static DataTable table;
private DataTable CreateData()
{
table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Number", typeof(int));
table.Rows.Add(new object[] { "one", 1 });
table.Rows.Add(new object[] { "two", 2 });
table.Rows.Add(new object[] { "three", 3 });
return table;
}
public DataTable Select()
{
if (table == null)
{
return CreateData();
}
else
{
return table;
}
}
public int Insert(NewData newRecord)
{
table.Rows.Add(new object[] { newRecord.Name, newRecord.Number });
return 1;
}
}
public class NewData
{
private string nameValue;
private int numberValue;
public string Name
{
get { return nameValue; }
set { nameValue = value; }
}
public int Number
{
get { return numberValue; }
set { numberValue = value; }
}
}
}
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Namespace Samples.AspNet.VB
Public Class AggregateData
Public Sub New()
End Sub
Shared table As DataTable
Private Function CreateData() As DataTable
table = New DataTable()
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Number", GetType(Integer))
table.Rows.Add(New Object() {"one", 1})
table.Rows.Add(New Object() {"two", 2})
table.Rows.Add(New Object() {"three", 3})
Return table
End Function
Public Function SelectMethod() As DataTable
If table Is Nothing Then
Return CreateData()
Else
Return table
End If
End Function
Public Function Insert(ByVal newRecord As NewData) As Integer
table.Rows.Add(New Object() {newRecord.Name, newRecord.Number})
Return 1
End Function
End Class
Public Class NewData
Private nameValue As String
Private numberValue As Integer
Public Property Name() As String
Get
Return nameValue
End Get
Set(ByVal value As String)
nameValue = value
End Set
End Property
Public Property Number() As Integer
Get
Return numberValue
End Get
Set(ByVal value As Integer)
numberValue = value
End Set
End Property
End Class
End Namespace
В следующем примере кода показана веб-страница, использующая два класса, которые используются в предыдущем примере кода.The following code example shows the Web page that uses the two classes that are used in the preceding code example.
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ObjectDataSource - DataObjectTypeName Property Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DetailsView
ID="DetailsView1"
runat="server"
AllowPaging="True"
AutoGenerateInsertButton="True"
DataSourceID="ObjectDataSource1"
Height="50px"
Width="125px">
</asp:DetailsView>
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
DataObjectTypeName="Samples.AspNet.CS.NewData"
InsertMethod="Insert"
SelectMethod="Select"
TypeName="Samples.AspNet.CS.AggregateData">
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ObjectDataSource - DataObjectTypeName Property Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DetailsView
ID="DetailsView1"
runat="server"
AllowPaging="True"
AutoGenerateInsertButton="True"
DataSourceID="ObjectDataSource1"
Height="50px"
Width="125px">
</asp:DetailsView>
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
DataObjectTypeName="Samples.AspNet.VB.NewData"
InsertMethod="Insert"
SelectMethod="SelectMethod"
TypeName="Samples.AspNet.VB.AggregateData">
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
Комментарии
Вместо указания нескольких параметров, передаваемых Update Insert Delete методам, и, можно создать один объект, который объединяет несколько значений полей данных.Instead of specifying several parameters that are passed to the Update, Insert, and Delete methods, you can create one object that aggregates several data field values. Этот один объект передается методам, а не нескольким параметрам.This one object is passed to the methods, instead of several parameters.
Поведением по умолчанию ObjectDataSource элемента управления, привязанного к элементу управления с привязкой к данным, является то, что элемент управления с привязкой к данным создает Parameter объект для каждого параметра в источнике данных.The default behavior of an ObjectDataSource control that is bound to a data-bound control is that the data-bound control creates a Parameter object for each parameter in the data source. Если у бизнес-объекта много полей, то у результирующего метода также будет много полей.If the business object has many fields, the resulting method also has many fields. DataObjectTypeNameСвойство позволяет указать тип, имеющий свойство для каждого поля данных.The DataObjectTypeName property allows you to specify a type that has a property for each data field. Затем, вместо передачи нескольких параметров в метод, среда выполнения создает один объект и задает все его свойства.Then, instead of passing several parameters to the method, the runtime creates one object and sets all of its properties. Этот один объект добавляется в коллекцию Parameters для вызова метода.This one object is added to the parameters collection for the method call.
Тип, заданный DataObjectTypeName свойством, должен иметь конструктор без параметров, не имеющий параметров, поэтому ObjectDataSource элемент управления может создать экземпляр типа.The type that is specified by the DataObjectTypeName property must have a parameterless constructor that has no parameters, so the ObjectDataSource control can create an instance of the type. Тип также должен иметь устанавливаемые свойства, позволяющие ObjectDataSource элементу управления заполнять объект значениями, передаваемыми из элемента управления с привязкой к данным.The type must also have settable properties that allow the ObjectDataSource control to populate the object with values that are passed from the data-bound control. Имена свойств ObjectDataSource элемента управления должны точно совпадать с именами параметров значений, передаваемых элементом управления с привязкой к данным.The property names on the ObjectDataSource control are expected to exactly match the parameter names of values that are passed by the data-bound control.
Если DataObjectTypeName свойство задано и ObjectDataSource элемент управления связан с элементом управления с привязкой к данным, то методы, заданные InsertMethod свойствами и, DeleteMethod должны иметь один параметр типа, указанный в DataObjectTypeName свойстве.When the DataObjectTypeName property is set and the ObjectDataSource control is associated with a data-bound control, the methods that are specified by the InsertMethod and DeleteMethod properties must each have one parameter of the type that is specified in the DataObjectTypeName property. Если ConflictDetection свойству присвоено OverwriteChanges значение, то метод, заданный UpdateMethod свойством, должен иметь один параметр типа, указанный в DataObjectTypeName свойстве.If the ConflictDetection property is set to the OverwriteChanges value, the method that is specified by the UpdateMethod property must have one parameter of the type that is specified in the DataObjectTypeName property. Если ConflictDetection свойству присвоено CompareAllValues значение, то метод, заданный UpdateMethod свойством, должен иметь два параметра типа, заданные в DataObjectTypeName свойстве.If the ConflictDetection property is set to the CompareAllValues value, the method that is specified by the UpdateMethod property must have two parameters of the type that is specified in the DataObjectTypeName property. Первый параметр содержит исходные значения; Второй параметр содержит новые значения.The first parameter contains the original values; the second parameter contains the new values.
DataObjectTypeNameСвойство делегирует DataObjectTypeName свойству объекта ObjectDataSourceView , связанного с ObjectDataSource элементом управления.The DataObjectTypeName property delegates to the DataObjectTypeName property of the ObjectDataSourceView that is associated with the ObjectDataSource control.
Применяется к
См. также раздел
- Элементы управления веб-сервером с источником данныхData Source Web Server Controls
- Общие сведения об элементе управления ObjectDataSourceObjectDataSource Control Overview
- Создание исходного объекта элемента управления ObjectDataSourceCreating an ObjectDataSource Control Source Object
- Использование параметров с элементом управления ObjectDataSourceUsing Parameters with the ObjectDataSource Control