ASP.NET Page Validation

Related article

By analogy with the above article, but a more specific note. How exactly you handle the elements that are in the viewstate (therefore, they are included in the submit), but can also be changed through AJAX. For example, let's say we had a drop-down list that was populated through an AJAX web service call (rather than an update panel). How can I get the page to check after changing the list items down?

+5
source share
3 answers

You do not check the drop-down list? You are checking the value selected by the user. This is almost the same advice as another post, since javascript or other tools can modify html or create your own POST, you should always check on the server side. Assume that all client requests are subject to change, and assume that the client-side check did not occur.


If you are using a web form model ...

If you just want to verify that the value is selected in the drop-down list myAjaxDropDown, use

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

You can also look at asp: CustomValidator - for server side validation:

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

Both connect to the asp.net validation framework. for example, when you press a button with the nameSumbitButton

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:

+3

Page_Validate() javascript, asp.net , Page.Validate()

+1

onChange ?

script onchange Page_Load

' 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)
0
source

All Articles