Call MVC 3 Client Side Validation Manually for ajax posts

后端 未结 8 611
长发绾君心
长发绾君心 2020-11-30 22:16

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 se

8条回答
  •  悲哀的现实
    2020-11-30 23:07

    I have been phaffing about with MVC client side validation for days:

    Don't use .click use .submit:

    $("#MyForm").on('submit',function () {
    
        if($("#MyForm").valid())
        {
            //Do ajax stuff
        }
    
        //Return false regardless of validation to stop form submitting
        //prior to ajax doing its thing
        return false;
    });
    

    I'm going add an update to this, consider cancelling the event rather than returning false (or do both):

    $("#MyForm").on('submit',function (e) {
    
        if($("#MyForm").valid())
        {
            //Do ajax stuff
        }
    
        e.preventDefault();
    
        //Return false regardless of validation to stop form submitting
        //prior to ajax doing its thing
        return false;
    });
    

提交回复
热议问题