ASP.NET Validation and jQuery
Recently I was working on a simple form that used the ASP.NET Validation controls for validation. This worked fine when doing a regular Postback to the server with the data. However I wanted to use Ajax to make it a little faster and the user experience better.
One of the problems I had was that when I hooked into my buttons click event with jQuery I needed to make sure the form validated before sending it to my web method. That’s when I came across this little piece of JavaScript.
if (Page_IsValid) { }
Which does the same thing as Page.IsValid on the server
Below is some simple sample code.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> <style type="text/css"> fieldset em { color: Red; } </style> </head> <body> <form id="form1" runat="server"> <fieldset> <p> <asp:Label runat="server" AssociatedControlID="txtName">Name: <em title="Required">*</em></asp:Label> <asp:TextBox runat="server" ID="txtName" ValidationGroup="Form" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="txtName" Text="Name is missing" ValidationGroup="Form" /> </p> <p> <asp:Button runat="server" ID="btnSend" Text="Submit" ValidationGroup="Form" OnClick="btnSend_Click" /> </p> </fieldset> <p id="result"> <asp:Literal runat="server" ID="ltlResult" /> </p> </form> <script type="text/javascript"> $("#<%= btnSend.ClientID %>").click(function() { if (Page_IsValid) { var name = $("#<%= txtName.ClientID %>").val(); $.ajax({ type: "POST", url: "Default.aspx/YourName", data: "{name:'" + name + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { $("#result").text(msg.d); } }); return false; } }); </script> </body> </html>
using System; using System.Web; using System.Web.Services; using System.Web.UI; public partial class _Default : Page { protected void btnSend_Click(object sender, EventArgs e) { if (Page.IsValid) { ltlResult.Text = string.Format("Your name is: {0}", HttpUtility.HtmlEncode(txtName.Text)); } } // Make sure to add the [WebMethod] attribute and make the method static [WebMethod] public static string YourName(string name) { return string.Format("Your name is: {0}", HttpUtility.HtmlEncode(name)); } }
The reason I still have the btnSend_Click method is in case the user does not have JavaScript enabled.
Hi buddy, your blog’s design is simple and clean and i like it. Your blog posts are superb. Please keep them coming. Greets!!!