ASP. NET code to bind data in batches and asp.net

Source: Internet
Author: User

ASP. NET code to bind data in batches and asp.net
Abstract: For the UI Layer of an application that focuses on data processing, we often need to write a lot of code to bind data. If some agreed ing relationships are stored between controls on the interface and entity types used as data sources, we can bind data in batches. The plug-ins developed by the author are used for this purpose, this article focuses on how to solve common problems in data binding through this component.

For the UI Layer of an application that focuses on data processing, we often need to write a considerable amount of code to bind data. If some agreed ing relationships are stored between controls on the interface and entity types as data sources, we can bind data in batches. To verify this idea, I wrote a small component. I spent only two hours writing this little thing, but there are still many problems that have not been solved, such as the processing of null values, the HTML encoding of special control attribute values, and the performance of frequent reflection, just demonstrate a solution. This article focuses on how to use this component to solve common problems during data binding. The next article will introduce its design. [Download the source code from here]

Directory:
1. Data Binding Based on Control ID/object property name ing
Ii. One sentence of code for Batch Data Binding
3. Modify the display format of bound data
4. Filter attributes that do not need to be bound
5. Multiple controls correspond to the same object property

1. Data Binding Based on Control ID/object property name ing

My current component is named DataBinder. web. UI. dataBinder), which is used to bind an object to all the child controls in the specified container control. The following is the definition of DataBinder. Two BindData methods are used for binding.

Public class DataBinder
{
Public event EventHandler <DataBindingEventArgs> DataItemBinding;
Public event EventHandler <DataBindingEventArgs> DataItemBound;

Public static IEnumerable <BindingMapping> BuildBindingMappings (Type entityType, Control container, string suffix = "");

Public void BindData (object entity, Control container, string suffix = "");
Public void BindData (object entity, IEnumerable <BindingMapping> bindingMappings );
}

As mentioned at the beginning of this article, automatic Batch Data Binding depends on the ing between controls and the entity types as data sources. Here, I directly use the ing between the control ID and the object property name. That is to say, when naming controls on the interface, they should be named according to the corresponding object type attribute name.

On the other hand, as a data source object, all its attributes are not involved in data binding. To enable DataBinder to automatically filter attributes for binding, I applied a custom attribute: DataPropertyAttribute. For example, the following Customer object will be used in subsequent demonstrations. Such a DataPropertyAttribute attribute is applied to each of its data attributes.

Public class Cutomer
{
[DataProperty]
Public string ID {get; set ;}
[DataProperty]
Public string FirstName {get; set ;}
[DataProperty]
Public string LastName {get; set ;}
[DataProperty]
Public string Gender {get; set ;}
[DataProperty]
Public int? Age {get; set ;}
[DataProperty]
Public DateTime? BirthDay {get; set ;}
[DataProperty]
Public bool? IsVip {get; set ;}
} 2. Bind data in batches with one sentence of code

Now we will demonstrate how to use the DataBinder we have defined to implement "Batch Data Binding of a code sentence", and as a data source, it is the Customer object we have defined above. Let's first design our page. below is the HTML Of the main part, which is a table. Note that the space to be bound to the Customer object has the same ID as the corresponding property.

<Table>
<Tr>
<Td style = "width: 20%; text-align: right"> ID: </td>
<Td> <asp: Label ID = "ID" runat = "server"> </asp: Label> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> First Name: </td>
<Td> <asp: TextBox ID = "FirstName" runat = "server"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Last Name: </td>
<Td> <asp: TextBox ID = "LastName" runat = "server"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Gender: </td>
<Td>
<Asp: RadioButtonList ID = "Gender" runat = "server" RepeatDirection = "Horizontal">
<Asp: ListItem Text = "Male" Value = "Male"/>
<Asp: ListItem Text = "Female" Value = "Female"/>
</Asp: RadioButtonList>
</Td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Age: </td>
<Td> <asp: TextBox ID = "Age" runat = "server"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Birthday: </td>
<Td> <asp: TextBox ID = "Birthday" runat = "server" Width = "313px"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Is VIP: </td>
<Td> <asp: CheckBox ID = "IsVip" runat = "server"> </asp: CheckBox> </td>
</Tr>
<Tr>
<Td colspan = "2" align = "center">
<Asp: Button ID = "ButtonBind" runat = "server" Text = "Bind" onclick = "ButtonBind_Click"/>
</Td>
</Tr>
</Table>

For convenience, the DataBinder object is used as an attribute of the Page type, which is initialized in the constructor.

Public partial class Default: System. Web. UI. Page
{
Public Artech. DataBinding. DataBinder {get; private set ;}
Public Default ()
{
This. DataBinder = new Artech. DataBinding. DataBinder ();
}
}

Then I will Bind the Data Binding operation according to the Click event, corresponding to all the Code as follows-the real code for data binding only has one sentence.

Protected void ButtonBind_Click (object sender, EventArgs e)
{
Var customer = new Customer
{
ID = Guid. NewGuid (). ToString (),
FirstName = "Zhang ",
LastName = "San ",
Age = 30,
Gender = "Male ",
BirthDay = new DateTime (1981, 1, 1 ),
IsVip = true
};
This. DataBinder. BindData (customer, this );
}

Open the Web page in the browser and click the Bind button. You will find that the bound data is correctly displayed in the corresponding control:

  3. Modify the display format of bound data

Although DataBinder is used to bind multiple controls in batches, it is not perfect. A notable problem is that the birthday field not only displays the date, but also the time. How can we display the date in the format we require? DataBinder provides three options.

If you see the DataBinder definition, you will find that it defines two events: DataItemBinding and DataItemBound (the name is subject to discussion), which are triggered before and after binding a control. Our first solution is to register the DataItemBinding time and specify a formatted string for Birthday. Suppose the format we need is "month-day-Year", then we specify the format string: MM-dd-yyyy. We registered the event in the Page constructor:

Public Default ()
{
This. DataBinder = new Artech. DataBinding. DataBinder ();
This. DataBinder. DataItemBinding + = (sender, args) =>
{
If (args. BindingMapping. Control = this. Birthday)
{
Args. BindingMapping. FormatString = "MM-dd-yyyy ";
}
};
}

Run the program and you will find that the birthday field has been displayed in the desired format:

The preceding describes how to specify the format string before binding by registering the DataItemBinding event. You can also modify the displayed date format after registering the DataItemBound event. The corresponding code is as follows:

Public Default ()
{
This. DataBinder = new Artech. DataBinding. DataBinder ();
This. DataBinder. DataItemBound + = (sender, args) =>
{
If (args. BindingMapping. Control = this. Birthday & null! = Args. DataValue)
{
This. Birthday. Text = (DateTime) Convert. ChangeType (args. DataValue, typeof (DateTime ))).
ToString ("MM-dd-yyyy ");
}
};
}

DataBinder defines two BindData reloads. We use the method of specifying data sources and container controls, and the other overload parameter is of the IEnumerable <BindingMapping> type. BindingMapping is a custom type used to indicate the runtime ing between controls and object attributes. Such a BindingMapping set can be created through the static method BuildBindingMappings of DataBinder. BindingMapping has a FormatString that represents the formatted string (in fact, the specified formatted string is specified for this attribute ). Then, we can use the following code to bind data:

Protected void ButtonBind_Click (object sender, EventArgs e)
{
Var customer = new Customer
{
ID = Guid. NewGuid (). ToString (),
FirstName = "Zhang ",
LastName = "San ",
Age = 30,
Gender = "Male ",
BirthDay = new DateTime (1981, 1, 1 ),
IsVip = true
};
Var bindingMappings = Artech. DataBinding. DataBinder. BuildBindingMappings (typeof (Customer), this );
BindingMappings. Where (mapping => mapping. Control = this. Birthday). First (). FormatString = "MM-dd-yyyy ";
This. DataBinder. BindData (customer, bindingMappings );
} 4. Filter attributes that do not need to be bound

By default, the first BindData method (specify the Container Control) traverses all attributes of the object and binds it to the corresponding control. Sometimes, we do not need to bind some special attributes. For example, although the IDs of a widget comply with the ing of object attributes, they do not represent data of the same nature.

To solve this problem, a Boolean AutomaticBind attribute is defined in the BindingMapping type. If you set this attribute to False before binding, Data Binding based on this BindingMapping will be ignored. If you call the BindData (object entity, Control container, string suffix = "") overload, you can set the AutomaticBind attribute of the corresponding BindingMapping to False by registering the DataItemBinding event. If you call the BindData (object entity, IEnumerable <BindingMapping> bindingMappings) overload, you only need to set the AutomaticBind attribute of the corresponding BindingMapping between calls to False.

We have restored our program to its initial state. Now, by registering the BindingMapping event, we can set the AutomaticBind attribute of BindingMapping Based on Birthday to False:

Public Default ()
{
This. DataBinder = new Artech. DataBinding. DataBinder ();
This. DataBinder. DataItemBinding + = (sender, args) =>
{
If (args. BindingMapping. Control = this. Birthday)
{
Args. BindingMapping. AutomaticBind = false;
}
};
}

After the program is executed, the TextBox corresponding to Birthday will not be bound:

  5. Multiple controls correspond to the same object property

In the above example, the ID of our control is the same as the corresponding object property. However, in many cases, more than one control maps to the same property of an object on the same page. The uniqueness of control IDs determines that we cannot create the same IDs for them. In this case, we use a "suffix-based" ing. That is, when naming a control, it is specified in the form of "object property name + suffix.

If you have carefully read the definition of DataBinder, whether it is the instance method BindData (which accepts the Control type parameter) or the static method BuildBindingMappings, there is a default parameter suffix, this is designed for this situation. By default, the value of this parameter is an empty string. Therefore, the control and Object Attributes must have the same name. If the control is named based on "object property name + suffix", You need to explicitly specify this parameter. To demonstrate this situation, we add the "_ Xyz" character to all the space IDs to be bound in this example as the suffix.

<Table>
<Tr>
<Td style = "width: 20%; text-align: right"> ID: </td>
<Td> <asp: Label ID = "ID_Xyz" runat = "server"> </asp: Label> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> First Name: </td>
<Td> <asp: TextBox ID = "FirstName_Xyz" runat = "server"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Last Name: </td>
<Td> <asp: TextBox ID = "LastName_Xyz" runat = "server"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Gender: </td>
<Td>
<Asp: RadioButtonList ID = "Gender_Xyz" runat = "server" RepeatDirection = "Horizontal">
<Asp: ListItem Text = "Male" Value = "Male"/>
<Asp: ListItem Text = "Female" Value = "Female"/>
</Asp: RadioButtonList>
</Td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Age: </td>
<Td> <asp: TextBox ID = "Age_Xyz" runat = "server"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Birthday: </td>
<Td> <asp: TextBox ID = "Birthday_Xyz" runat = "server" Width = "313px"> </asp: TextBox> </td>
</Tr>
<Tr>
<Td style = "width: 20%; text-align: right"> Is VIP: </td>
<Td> <asp: CheckBox ID = "IsVip_Xyz" runat = "server"> </asp: CheckBox> </td>
</Tr>
<Tr>
<Td colspan = "2" align = "center">
<Asp: Button ID = "ButtonBind" runat = "server" Text = "Bind" onclick = "ButtonBind_Click"/>
</Td>
</Tr>
</Table>

If you use the specified Container Control for direct binding, you can program it like this:

Protected void ButtonBind_Click (object sender, EventArgs e)
{
Var customer = new Customer
{
ID = Guid. NewGuid (). ToString (),
FirstName = "Zhang ",
LastName = "San ",
Age = 30,
Gender = "Male ",
BirthDay = new DateTime (1981, 1, 1 ),
IsVip = true
};
This. DataBinder. BindData (customer, this, "_ Xyz ");
}

If you bind data through the pre-created BindingMapping collection, the code will be as follows:

Protected void ButtonBind_Click (object sender, EventArgs e)
{
Var customer = new Customer
{
ID = Guid. NewGuid (). ToString (),
FirstName = "Zhang ",
LastName = "San ",
Age = 30,
Gender = "Male ",
BirthDay = new DateTime (1981, 1, 1 ),
IsVip = true
};

Var bindingMappings = Artech. DataBinding. DataBinder. BuildBindingMappings (typeof (Customer), this, "_ Xyz ");
This. DataBinder. BindData (customer, bindingMappings );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.