views:

1529

answers:

3

Related Article

On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?

A: 

why not validating onChange even in the dropdownlist?

just add the script manager and add that property to the onchange in the Page_Load event

' Creating the javascript function to validate
Dim js As String
js = "function validateDDL1(ddl) { alert(ddl.value); }"

' Adding onChange javascript method
DropDownList1.Attributes.Add("onchange", "validateDDL1(this);")

' Registering the javascript
ScriptManager.RegisterClientScriptBlock(Me, GetType(String), "validateDDL1(ddl)", js, True)
balexandre
+1  A: 

You can call the Page_Validate() function from your javascript code, it will trigger the asp.net validators on the page, it is basically similar to Page.Validate() in server code

bashmohandes
+3  A: 

You're not validating the dropdown list are you? You're validating the value a user selected. It's pretty much the same advice as the other post, since javascript or other tools can alter the html or create their own POST's, you must always validate on the server side. Assume all client requests can be tampered with, and assume that no client-side validation has occurred.


If you're using the web forms model ....

If you just want to check a value was selected in the dropdown myAjaxDropDown , use the

<asp:RequiredFieldValidator id="dropdownRequiredFieldValidator"
          ControlToValidate="myAjaxDropDown"
          Display="Static"
          InitialValue="" runat=server>
          *
        </asp:RequiredFieldValidator>

You could also want to look at the asp:CustomValidator - for server side validation:

<asp:CustomValidator ID="myCustomValidator" runat="server" 
    onservervalidate="myCustomValidator_ServerValidate" 
    ErrorMessage="Bad Value" />

Both plug into the validation framework of asp.net. e.g. when you click a button called SumbitButton

protected void myCustomValidator_ServerValidate(object source, ServerValidateEventArgs e)
{
    // determine validity for this custom validator
    e.IsValid = DropdownValueInRange(myAjaxDropDown.SelectedItem.Value); 
}

protected void SubmitButton_Click( object source, EventArgs e )
{
    Validate(); 
    if( !IsValid )
        return;

    // validators pass. Continue processing.
}

Some links for further reading:

Robert Paulson