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 ()
{
$.validator.unobtrusive.parse('#my-form');
$("#my-form").submit(SubmitForm);
});
And in my submit function, I can do the processing of my own forms:
function SubmitForm(e)
{
e.preventDefault();
var valid = $("#my-form").validate();
if (valid.errorList.length > 0)
return;
var formData = ...(code removed for clarity)
$("#ajax-loader").css("display", "inline")
$.post(
'@Url.Action("MyAction", "MyController")',
formData,
SuccessFunction
)
.error(ErrorFunction);
}
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 .