Dynamically created Partial View does not call controller action on submit

Question!

I am using AJAX to replace bootstrap modal content with a partial view like this:

Main View HTML

   <div class="container row form-horizontal">
        <div id="myModal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content" id="myModalContent">

                </div>
            </div>
        </div>
    </div>

AJAX script inside main view

  $(function () {
    $.ajaxSetup({ cache: false });
    $(document).on('click', 'a[data-modal]', function (e) {
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                keyboard: true
            }, 'show');
            bindForm(this);

            $("form").removeData("validator");
            $("form").removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse("form");

        });



        return false;
    });
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        $('#progress').show();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    $('#progress').hide();
                    alert('reloading');
                    location.reload();
                } else {
                    $('#progress').hide();
                    $('#myModalContent').html(result);
                    bindForm();
                }
            }
        });
        return false;
    });
}

Partial View HTML

@model MVC_Replica.Models.Location

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 class="modal-title">Add New Location</h3>
</div>


@using (Html.BeginForm("Create","Locations",FormMethod.Post))
{
@Html.AntiForgeryToken()

<div class="modal-body">

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.LocationName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LocationName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LocationName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DateCreated, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DateCreated, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LocationState, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LocationState, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LocationState, "", new { @class = "text-danger" })
            </div>
        </div>


    </div>
</div>
<div class="modal-footer">
    <span id="progress" class="text-center" style="display: none;">
        <img src="~/media/ajax-loading.gif" alt="wiat" />
        Wait..
    </span>

    <input type="submit" class="btn btn-primary pull-left" value="Create" />
    <button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>

}

Result

The modal opens correctly and client side validation works perfectly well. However, when i submit the partial view, the following controller action is never executed:

        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Location location)
    {
        if (ModelState.IsValid)
        {
            location.DateCreated = DateTime.Now;
            db.Locations.Add(location);
            db.SaveChanges();
            return Json(new { success = true });
        }

        return PartialView("_CreateLocation", location);
    }

I tried placing a brake point next to ModelState.IsValid but it never gets hit.Also the browser console is not displaying any errors

What could be the problem?

Edit

I managed to get the partial view to call the create action controller by storing anchor href value in a global variable and changing the bindForm function:

 var actionUrl;
$(function () {

    $('form').submit(function () {

       // alert(this.action);
    });
    $.ajaxSetup({ cache: false });
    $(document).on('click', 'a[data-modal]', function (e) {
        actionUrl = this.href;

        $('#myModalContent').load(this.href, function () {

            $('#myModal').modal({
                keyboard: true
            }, 'show');

            bindForm();

            $("form").removeData("validator");
            $("form").removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse("form");

        });

        return false;
    });
});
function bindForm() {
    $('form').on('submit',function () {

        $('#progress').show();
        $.ajax({
            url: actionUrl,
            type: 'POST',
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    $('#progress').hide();

                    location.reload();
                } else {
                    $('#progress').hide();
                    $('#myModalContent').html(result);
                    bindForm();
                }
            }
        });
        return false;
    });
}


Answers
So the reason why the create controller action was never invoked, was because the submit event of the bindForm function was never being executed. As i have discovered, the dialog selector in the bindForm function stopped the event from being triggered. I have added an edit to the question explaining a possible solution.



This video can help you solving your question :)
By: admin