Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - Call MVC 3 Client Side Validation Manually for ajax posts

I am creating an MVC 3 web application. I want to use Data Annotations on my entity class and then use unobtrusive client side validation before making a post back to the server. This works fine when making a regular post. I get validation and the validation summary if any of the fields are not valid. However, I want to post back the information via ajax and json. How can I 'manually' validate the form on the client side first then make my ajax post back to the server. Below is a summarized version of my code.

  public class Customer
    {
        [Required(ErrorMessage = "The customer's first name is required.")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "The customer's last name is required.")]
        public string LastName { get; set; }
    }



    <% using (Html.BeginForm()) { %>

    <%: Html.LabelFor(model => model.FirstName, "First Name")%>
    <%: Html.TextBoxFor(model => model.FirstName, new { @class = "TextBox", id = "Customer.FirstName" })%>
    <%: Html.ValidationMessageFor(model => model.FirstName, "*")%>

    <%: Html.LabelFor(model => model.LastName, "Last Name")%>
    <%: Html.TextBoxFor(model => model.LastName, new { @class = "TextBox", id = "Customer.LastName" })%>
    <%: Html.ValidationMessageFor(model => model.LastName, "*")%>

    <div id="CustomerEditSave" class="Button CustomerEditButtons" style="margin-right:40px;">
       <a href="#">Save</a>
    </div>

    <%: Html.ValidationSummary(true) %>

    <% } %>

I have tried this code but it only validates the first name and does not display the validation summary.

    $("#CustomerEditSave").click(function () {
        $(form).validate();
        //Ajax call here
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

//using the form as the jQuery selector (recommended)
$('form').submit(function(evt) {
    evt.preventDefault();
    var $form = $(this);
    if($form.valid()) {
        //Ajax call here
    }
});

//using the click event on the submit button
$('#buttonId').click(function(evt) {
    evt.preventDefault();
    var $form = $('form');
    if($form.valid()) {
        //Ajax call here
    }
});

This should work with jQuery ajax and MSAjax calls. Could also try using http://nuget.org/packages/TakeCommand.js or https://github.com/webadvanced/takeCommand it will automatically handle this for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...