ASP. NET binds the data to DrowdownList and decodes the data using HTML encoding.

Source: Internet
Author: User

1. Problem background

During Web development, you need to verify and filter user input data to prevent injection attacks. A common method is filtering and encoding.

Filtering means to filter the sensitive characters entered by the user. You can restrict the user's input of sensitive characters and automatically delete the sensitive characters. Limiting the user's input will lead to user dissatisfaction, in this case, you cannot enter the password, but deleting the password automatically will change the user's content, and the user experience may be worse or even change the meaning, the two methods are not the best choice for non-strict input, such as the financial system and crm.

The encoding method is to encode the content entered by the user, store it in the database, and then directly display it on the HTML page, or decode it and display it in the text box. There are no strict restrictions, does not change the user input.

However, a problem occurs when binding ASP. NET data.

ASP. NET data binding requires only a few lines, that is

The code is as follows: Copy code
DropDownList. DataSource = datasource;
 
DropDownList. DataTextField = textField;
 
DropDownList. DataValueField = valueField;
 
DropDownList. DataBind ();

However, the following problems may occur in the encoded data source,


There is a category as shown in the following figure.

However, binding to the DrondownList application causes the following problems:
 


2 Solutions

Perform HTML decoding on the bound data items, that is, rewrite the DataBound time. This article uses anonymous delegation to implement

The code is as follows: Copy code

DropDownList. DataBound + = delegate (object sender, EventArgs e)
                {
Int I = 0;
ListControl list = sender as ListControl;
Foreach (ListItem l in list. Items)
                    {
L. Text = l. Text. ToHtmlDecode ();
I ++;
                    }
};

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.