How to submit ASP NET MVC3 Form through ajax while overriding default behavior while maintaining client side validation
I want to be able to post this form data using an ajax post, but I cannot figure out how to override the default behavior when the form is posted. I still want client side validation from ASP NET MVC3 though. For example, when I click "submit" in this form, it goes directly to the controller action when I have a jquery function that is supposed to directly handle any submit from this form.
@model BlogApp.Models.PostUser
@using (Html.BeginForm("LoginForm", "Home", FormMethod.Post, new { id = "testform" }))
{
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name,开发者_运维百科 new { id = "Name" })
@Html.ValidationMessageFor(model => model.Name)
</div>
<input type="submit" value="submit" />
</fieldset>
}
this is the jquery function:
$('#testform').live('submit', function () {
$('#testform').validate();
var name = $('#Name').val();
var logout = '<a href="#" onClick="logOut()">logout</a>';
var login_success = '<p>Logged in as: ' + name + '</p>' + logout;
if ($(this).valid()) {
$.ajax({
url: '/home/loginform',
type: 'POST',
data: { name: name },
success: function (data) {
if (data === true) {
$('#loginform').empty();
$('#loginform').append(login_success);
}
else {
alert('Failed to save the user');
}
}
});
}
});
So my question is: instead of the form automatically going to the controller action (/Home/LoginForm/) and returning that result, how can I make submitting the form fire my jquery function (so that the page doesn't auto-refresh), but still maintaining the client side validation?
The <input type="submit" value="submit" />
is probably the culprit. The default form submission is occurring because of the input type submit. You could change your submit button to be a different html tag (like a span) and then use JQuery to assign the click event to handle your submission, or you could cancel the default action within your submit handler you have now (see the .submit() documentation for JQuery on how to do that).
...we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler
精彩评论