简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM