Mixing Microsoft MVC ajax and validation helpers with native jquery ajax

Introduction

This is a post about mixing Microsoft MVC helpers with built-in jquery ajax. The main problems that I encountered along the way were:

  • Double messages
  • @ Html.ValidationMessage Attributes for output without output

Requirements

  • I have a requirement to verify and publish the form (id = "my-form")

  • The form is tied to a model decorated with validation attributes, so I want to use helper methods like @ Html.ValidationMessage to take advantage of the unobtrusive benefits

  • I need a client-side and server-side check (on the server side I do a unique name check using the database)

  • I need to do client-side processing when submitting a form to add additional form data.

Iterative steps

STEP 1

I started with my own built-in jquery and used the Microsoft assistant to create an ajax form:

@using (Ajax.BeginForm( ...

All worked as advertised. This gave me an unobtrusive confirmation, but it did not meet my requirements for sending data on the form.

So, I thought I would redefine the sending process.

STEP 2

In my document, I’m ready to hook up a new event handler:

$(document).ready(function () 
{
    // Rebind validators
    $.validator.unobtrusive.parse('#my-form');

    // Hook up submit event
    $("#my-form").submit(SubmitForm);
});

And in my submit function, I can do the processing of my own forms:

function SubmitForm(e) 
{
    // Suppress normal event behaviour
    e.preventDefault();

    // Validate the form
    var valid = $("#my-form").validate();
    if (valid.errorList.length > 0)
        return;

    // Collect up form data manually
    var formData =  ...(code removed for clarity)

    // Display animated gif
    $("#ajax-loader").css("display", "inline")

    // Post Form
    $.post(
            '@Url.Action("MyAction", "MyController")',   // url
            formData,                                   // data
            SuccessFunction                             // success
        )
        .error(ErrorFunction);                         // error
}

So the scene is now set.

Problem

, ajax. . , . ( micosoft jquery) , 2 . Google, , jquery, .

3

, @using (Ajax.BeginForm(...) :

<form id = "my-form">
   ...
</form>

@Html.ValidationMessageFor . firebug, , .

@Html.ValidationMessageFor, , .

Ajax.BeginForm(... .

4

, :

 @using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { id = "my-form" })) 
 {....

Html.BeginForm , @Html.ValidationMessageFor . "MyAction" "MyController" , .

.

  • @Html.ValidationMessageFor
  • /

.

? , - elses .

+3
1

, Fluent Validation. , , , JQuery, / . , , , . , . ajax, html, , , Ajax.Beginform. Beginform .

, HTML Helpers, div .

, , . , . , .

0

All Articles