Callback from jQuery not getting to Controller/Action

前端 未结 1 896
日久生厌
日久生厌 2021-01-21 08:18

I have a contact us form in a modal dialog box using jQuery in an MVC application. The box popups up fine, but when I click on the submit button in the dialog box, its not gett

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 08:52

    You dynamically adding the form to the DOM using .load(this.href); which means you need to use event delegation to handle the button. Change

    $(".close").on("click", function (e) {
    

    to

    $(document).on('click', '.close', function(e) {`
    

    although you should replace document with the closest ancestor that exists on the page when you first render the view.

    In addition, your jQuery selectors are incorrect and you will not be posting any values related to your model. The correct selectors are based on the id attributes generated by the HtmlHelper methods are

    var senderName = $("#senderName").val();
    var senderEmail = $("#senderEmail").val();
    var message = $("#message").val();
    

    however its better to use the .serialize() method which will correctly serialize your form controls

    $.ajax({
        type: "POST",
        url: '@Url.Action("SendEmail", "Home")', // don't hard code
        data: $('#sendEmailForm').serialize(),
        success: function (data) {
            ....
    

    0 讨论(0)
提交回复
热议问题