We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy.
Unfortunately, activation email could not send to your email. Please try again.

How to enable the Unobtrusive Jquery validation for a form in MVC on page transfer?

In MVC, form validation is achieved by using its built-in jquery unobtrusive validation. The form validation does not work when a page is transferred via the Ajax request. You can enable the validation in the viewtransfer event. To achieve this, refer to the following steps.

  1. Create a model file to the application. This consists of jquery validation rules. You can refer to the following code example. 

Sample.cs

public class Sample

    {

        [Required]

        public string Name { get; set; } 

        [Required]

        [EmailAddress]

        public string Email { get; set; }

    }

  1. Create the form with unobtrusive error message. Refer to the following code example.

Index.cshtml

<form>

    @Html.LabelFor(model => model.Name)

    @Html.TextBoxFor(model => model.Name)

    @Html.ValidationMessageFor(model => model.Name)

    <br />

    @Html.LabelFor(model => model.Email)

    @Html.TextBoxFor(model => model.Email)

    @Html.ValidationMessageFor(model => model.Email)

    <br />

    <input type="submit" value="Submit" />

</form>

  1. To enable form validation after the Ajax page transfer, add the following script code to the active page. This recalibrates all the validators of the form elements when content is added dynamically.

Script

 <script>

    $(document).bind("viewtransfer", function () {

        $('form').removeData('validator');

        $('form').removeData('unobtrusiveValidation');

        $.validator.unobtrusive.parse('form');

    });

</script>

 

Article ID: Published Date: Last Revised Date: Platform: Control:
4101 02/19/2015 02/19/2015 ASP.NET MVC General
Tags:
Did you find this information helpful?
Add Comment
You must log in to leave a comment

You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.