5 Comments
  • Posted in:
  • C#

This blog post is all about how to make a nice form and have client side validation with jQuery and the famous validation plugin. After validation the data, the form will be posted asynchronous to an Asp.Net C# Webservice/webmethod. While the post is being processed, a nice loading image will be displayed to notify the user of the progress. [more]

Add jQuery

First you have to add jQuery to the form. This can be done by downloading a version from jQuery.com (option 1) or get jQuery as Nuget Package or (option 2) get jQuery from a CDN (Content Delivery Network) (option 3) so that the request is being handled by the closest server based on Geolocation. This approach has also another benefit called browser caching.

option 1:

1. go to http://jquery.com/ and right click download and select ‘save-as’

2. save in your javascript folder of your solution

3. add a reference in your form page

 

Pro:Just a few easy steps, things won’t break if there is a newer version.

Con:No CDN, no auto update

 

option 2:image

1. install Nuget from http://nuget.org/

2. restart visual studio

3. click project

4. click manage nuget packages

5. type in the search box on the top right: jQuery

6. click on install

7. add a reference in your form page

optional: view the package info online on nuget.org: http://nuget.org/List/Packages/jQuery

 

Pro: Nuget will update the library if there is a new version

Con: No CDN, requires a small but awesome extension for Visual Studio

 

option 3:

1. Choose between networks (Google or Microsoft)

2. Add a reference to either

https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

or

http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js

Google CDN: http://code.google.com/apis/libraries/devguide.html#jquery

Microsoft CDN: http://www.asp.net/ajaxlibrary/CDN.ashx#Using_jQuery_from_the_CDN_12


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

Pro: Geo benefit, Browser Cache, saves your bandwith

Con: No auto update

Adding validation

The next step is to add a nice jQuery plugin called ‘validation’. This plugin is maintained by a member of the jQuery team. His name is Jörn Zaefferer. You can get it from his website:

http://jquery.bassistance.de/validate/jquery-validation-1.8.1.zip

and you can read more about it on his site:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

His plugin is also available through Nuget and the Microsoft CDN (not Google’s)

http://nuget.org/List/Packages/jQuery.Validation

Extract the zip and add the file ‘jquery.validate.min.js’ to your Javascript folder in your solution and add a reference to it.

<script src="js/jquery.validate.min.js" type="text/javascript"></script>

I have attached an example of how I made a simple form with jQuery 1.6 from the Google CDN and the validation plugin.

$(document).ready(function () {
    $('#sub').click(function () {
    var container = $('div.error');

    var validator = $("#form1").validate({
        errorContainer: container,
        errorLabelContainer: $("ul", container),
        ignore: ":not(:visible)", // if you have input fields in your form which are temp invisible
        wrapper: 'li',
        rules: {
            tbMail2: { equalTo: "#tbMail1", required: true, email: true }
        },
        messages: {
            tbMail2: "The mailadresses are not the same!"
        }
    });
    if ($("#form1").valid()) {
        alert('ok nice!');
    }
    else {
        alert('this is optional, the error is shown below');
    }
});
});

This is the HTML for my simple form:

<form id="form1">
    <fieldset>
        <legend>Personal Information</legend>
        <label for="fname">First Name:</label>
        <input type="text" name="firstname" id="fname" class="required"/>
        <label for="tbMail1">E-Mail:</label>
        <input type="text" name="mail1" id="tbMail1" class="required email"/>
        <label for="tbMail2">E-Mail again:</label>
        <input type="text" name="mail2" id="tbMail2" class="required email"/>
        <input id="sub" type="submit" value="Send"/> <input type="reset"/>
    </fieldset>
</form>
<div class="error" style="display: none;">
    <h2>Something goes wrong!</h2>
    <ul>
        <li><label for="fname" class="error">Please fill in your firstname</label></li>
        <li><label for="tbMail2" class="error">The second mailadres is an invalid adress</label></li>
    </ul>
</div>

As you might notice, I haven't added an error message in the container for all form elements. All form elements are required fields and two are marked as email. Those classes can be found in the documentation of the validation plugin.

I added an image from http://www.ajaxload.info/ as loading image and added the style=”display:none;” When the validation has succeeded, the image will be faded in. and when the Ajax JSON post has completed, it will be faded out.

Here is my Asp.Net ASMX file which will handle the AJAX JSON request and will return an URL.

using System;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class myAjaxHandler : WebService
{
    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string ProcessSampleForm(string first, string mail, string mailinglist)
    {
        // sample code
        bool mailingList = false;
        bool.TryParse(ml, out mailingList);
        string redir = "youraccount.aspx";
        if(first.Contains("admin"))
            redir = "admin/admin.aspx";
        
        return redir;
    }
}

To call this ASMX, I used jQuery. It's very easy to make Async calls with jQuery and combine it with Asp.Net logic.

if ($("#form1").valid()) 
{
    $(".loadingimg").fadeIn();
    var dataString = "{ 'first' : '" + escape($('#fname').val()) + 
        "', 'mail' : '" + escape($('#tbMail1').val()) + 
        "', 'mailinglist' : '" + $("input[name='ml']:checked").val() + 
        "' }";
        /*alert(dataString.replace('\',','\',\n'));*/ // just for debugging ;)
    $.ajax({
        type: "POST",
        url: "myAjaxHandler.asmx/ProcessSampleForm",
        data: dataString,
        cache: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $(".loadingimg").fadeOut();
            window.location.replace(msg.d);
        },
        error:function(xhr,err){
            $(".loadingimg").fadeOut();
            alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    });
}

Please let me know in the comments if this will work for you. I will attach the full source code below:

Summary

Use HTML5! Add the jQuery library by one of the three options mentioned in this post. Add the jQuery validation plugin. Use jQuery to validate your form and if it's validated, send a JSON string asynchronously to an Asp.Net (C#) Asmx and process the result of the method in jQuery again. Also use nice gif images to let users know that something is currently running.

Good luck!

kick it on DotNetKicks.com Shout it

Pin on pinterest Plus on Googleplus Post on LinkedIn

Comments

Comment by DotNetKicks.com

JQuery with webform input validation, ajax posting json to asp.net C#

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Comment by DotNetShoutout

JQuery with webform input validation, ajax posting json to asp.net C

Thank you for submitting this cool story - Trackback from DotNetShoutout

Comment by syngu.com

Pingback from syngu.com

JQuery with webform input validation, ajax... | .NET, jQuery | Syngu

Comment by programmersgoodies.com

Pingback from programmersgoodies.com

Accessing Data in Httphandler sent using post request - Programmers Goodies

Comment by JP Hellemons

@Meera,

Add this in your HTML: <img src="yourloading.gif" alt="loading" style="display:none;" class="loadingimg" />

because in my jQuery sample, you fadeIn and fadeOut the class 'loadingimg'

JP Hellemons