Implemation Jquery Dialog client validation and server validation in Asp.net mvc 3

Hi,

This article intended to show how to implement Jquery Dialog validation within ASP.net MVC 3, it will skip the steps of how implementing jquery UI dialog, there are many articles around to cover about it.

What I want to do here is to implement the jquery dialog which gets data from a partialview, it will then validate the inputs then send it to the ActionController via an Ajax call

Here are the main steps:

  1. Render a Jquery Dialog from PartialView
  2. Validate on client side (if datas are required or not)
  3. Send the datas over as Ajax Call/Json to the server to validate it

In order to reduce http calls, ones need to validate as much as possible on client before sending datas to server validation.

Here is what is done for validation:

Client Validation

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

<button id="btnDialog">Account Logon</button>

<div id="Logonform"></div>

<script type="text/javascript">

    $(document).ready(function () {

        $.validator.unobtrusive.parse('#Logonform');

        $("#Logonform").dialog({
            autoOpen: false,
            modal: true,
            title: 'Login',

            buttons: {
                Save: function () {
                    //alert($('form').serialize());
                    //alert($("#Logonform").attr('UserName'));

                    if ($('form').validate().form()){
                        $.ajax({
                            url: "@Url.Action("LogOn", "Account")",
                            type: "POST",
                            data: $('form').serialize(),
                            datatype: "json",
                            success: function (result) {
                                $("#Logonform").html(result).dialog('open');
                            }
                        });
                    }
                },

                Close: function () {
                    $(this).dialog('close');
                }
            }

        });

        $("#btnDialog").click(function () {
            $.ajax({
                url: "@Url.Action("LogOn", "Account")",
                type: "GET",
                success: function (result) {
                    $("#Logonform").html(result).dialog('open');
                }

                });
        });
    })

</script>

As you can see, there is a need to implement

  • $.validator.unobtrusive.parse(‘#Logonform’); to activate unobstrusive javascript within the project
  • include the 2 javascript libraries:
  • <script src=”../../Models/Scripts/jquery.validate.min.js” type=”text/javascript”></script> <script src=”../../Models/Script/jquery.validate.unobtrusive.min.js” type=”text/javascript”></script>
  • Before the Ajax call, client validation with if ($(‘form’).validate().form()){ }

Here is the model

    public class LogOnModel
    {
        [Required]
        [Display(Name = "Nom d'utilisateur")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Mot de passe")]
        public string Password { get; set; }

        [Display(Name = "Mémoriser le mot de passe ?")]
        public bool RememberMe { get; set; }
    }</

Server validation

The server validation is very much straightforward, check if the ModelState is valid, then processing the datas, if error, Add error collection to the ModelState and return back the errors with the partialView

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    return Json( new { result = "ok", user = model.UserName });
                }
                else
                {
                    ModelState.AddModelError("", "Le nom d'utilisateur ou mot de passe fourni est incorrect.");
                }
            }

            // Si nous sommes arrivés là , quelque chose a échoué, réafficher le formulaire
            return PartialView("_Logon");
       }

Code source can be found here:

http://dl.dropbox.com/u/9847533/JqueryDialogTest.zip

Others interesting articles to read:

http://nickstips.wordpress.com/2011/08/11/asp-net-mvc-ajax-dialog-form-using-jquery-ui/

http://cdsmithon.net/2012/03/27/ajax-form-submission-in-mvc-3-0/

About these ads
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

One Response to Implemation Jquery Dialog client validation and server validation in Asp.net mvc 3

  1. Tuoski says:

    Thank you!
    Have see many examples of how to do this, but this was the first one that actually works.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s