0

I am loading a from dynamically onto the page, I then setup the event to capture and handle the form submit.

But for whatever reason the form, still does the usual post and goes to the page instead of the ajax post.

I'm pretty sure its all correct but can't figure out why?

I load the form dynamically like this:

$('body').on('click', 'a[data-toggle="modal"]', function (e) {
    var action = $(this).attr('href');

    $.ajax({
        url: action,
        type: "GET",
        success: function (response) {
            $('<div class="modal fade"></div>').html(response).modal();
            hookupFormSubmit();
        }
    });

    e.preventDefault();
});

hookupFormSubmit looks like this:

var hookupFormSubmit = function () {

    $('.modal-dialog').on('submit', 'form', function (event) {
        event.preventDefault();

        var $form = $(this);

        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {

                $form.closest('.modal').modal('hide');

            }
        });

    });
};

And my form itself:

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Modal title</h4>
        </div>
        <div class="modal-body">
            @using (Html.BeginForm())
            {
                @Html.ValidationSummary(true)
                @Html.EditorForModel()
                <p>
                    <input type="submit" value="Send Message!" />
                </p>
            }
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
</div>
shenku
  • 11,969
  • 12
  • 64
  • 118

3 Answers3

1

replace

$('.modal-dialog').on('submit', 'form', function (event) { 

with

$('.modal').on('submit', 'form', function (event) {
Jeetendra Chauhan
  • 1,977
  • 2
  • 15
  • 21
0

i guess you set form runat="server" thats why form is submitting every time. i suggest if not runat="server" is not required. remove this attribute from Form tag

Harjeet Singh
  • 388
  • 2
  • 6
  • 22
0

When you create the dialog, you're not inserting the html into the DOM.

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97