Dropdown List anomaly in asp.Net
For the first time in ages, I was stumped by what seemed like a trivial issue with formatting and a pesky ampersand. The problem was that when users selected an item from a dropdown list that had a & character in it. The result was a rather unfriendly validation error thrown by asp.Net.Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation=“true”/>'
Now there is a very easy solution to this, and it involves setting the <pages enableEventValidation=“false”/>', but this wasn't optimal as it would leave the page open to cross site scripting attacks. I set about trying to HtmlEncode the postback value to escape the troublesome characters. In hindsight this was never going to work, but it did lead me down another path. After some googling to old blog posts and a few examples on stackoverflow (mainly revolving around Javascript) I thought I'd found the answer I was after.protected override void Render(HtmlTextWriter writer) { //register the items from the dropdownlist as possible postbackvalues for the listbox foreach (ListItem option in ddAssignedTo.Items) { Page.ClientScript.RegisterForEventValidation(ddAssignedTo.UniqueID, option.Value); } base.Render(writer); }This still didn't work, and I was about to admit defeat and just set the EventValidation to false. I stepped through the code to check what values were being sent back to the page and I was quite shocked. The Values being posted back didn't match the values in the dropdownlist. It was a subtle difference but the Dropdownlist had removed additional spaces from the raw data.
At first I thought it was some funky javascript one of the front end guys had put into the code but it turns out this wasn't the case. IE actually had an override on the Rendering of the Controls that removes this additional whitespace. The trouble is, the Validation Values assigned to the controls happen after this has taken place.
Unfortunately I was unable to change the data in the database so I had to change my code to accommodate this feature of the web Rendering the page. I had two options. Strip the additional whitespace before assigning the value to the listitem in the dropdown box, or somehow force the dropdown to keep the additional spacing. I opted for the latter and used the <Pre> tag to ensure that all Text and Values in the Dropdown List were treated as strict values.
I am unsure if this affects other controls at the moment but I will run some simple tests when I get some downtime and append to this blog with my findings.