Call MVC 3 Client Side Validation Manually for ajax posts

后端 未结 8 577
长发绾君心
长发绾君心 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;
    });
    
    0 讨论(0)
  • 2020-11-30 23:09
    I tried all of the above solutions but none worked on MVC5. 
    

    I am using jQuery v2.1.4 and jQuery.Validation v1.11.1. I need to trigger validation while on page render. Only below one worked for me.

    $(document).ready(function () {
       ...
       validateForm();
    }
    
    function validateForm() {`enter code here`
        var elem = document.getElementById('btnSave');
        elem.click();    
    }
    
    $('#btnSave').click(function (evt) {
        //evt.preventDefault();
        var form = $('form');
        if (form.valid()) {
            //Ajax call here
        }
        //$(".validation-summary-errors").css("display", "block");
    });
    
    function Validate() {
        // If no group name provided the whole page gets validated
        Page_ClientValidate();
    }
    
    0 讨论(0)
提交回复
热议问题