ASP.NET validation issue - DropDownList is dynamically populated by client
I am populating a DropDownList using JS on the client and validating with RequiredFieldValidator.
This works fine on the client, but Page.IsValid consistently returns false on the server.
Is it because the selected value was not in the DropDownList when it was first submitted to the page?
What's the easiest way? (I need to leave server validation enabled)
a source to share
Is it because the selected value was not in the DropDownList when it was first served on the page?
Yes. You will probably notice that your dropdownlist will contain no elements when you do your postback, and yes, that is because you are adding your elements on the client side. Any items that you add to a control on the client are completely unknown to the server. Therefore your server validation will always fail as this field is required.
In fact, adding elements dynamically using a client script will trigger EventValidation to complain about a possible security issue and you will have to set EnableEventValidation
in false
to your directive <%@ Page %>
to be able to post.
The best way to get around this:
-
Create your items server side or
-
Don't use a server control to do this (use a normal netapswa picklist) and manually validate it on the server by looking at the published values.
a source to share