动态创建的部分视图不会在提交时调用控制器操作

时间:2016-02-18 12:32:27

标签: jquery ajax asp.net-mvc twitter-bootstrap partial-views

我正在使用AJAX用这样的部分视图替换bootstrap模态内容:

主视图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脚本

  $(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;
    });
}

部分查看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>

}

结果

模态正确打开,客户端验证工作正常。但是,当submit partial view时,以下控制器操作永远不会执行:

        [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);
    }

我尝试在ModelState.IsValid旁边放置制动点,但它永远不会被击中。浏览器控制台也没有显示任何错误

可能是什么问题?

修改

我设法通过在anchor中存储href global variable值并更改bindForm函数来获取部分视图以调用创建操作控制器:

 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;
    });
}

1 个答案:

答案 0 :(得分:0)

因此永远不会调用create controller action的原因是因为submit函数的bindForm事件从未被执行过。正如我所发现的,dialog函数中的selector bindForm阻止了事件被触发。我在问题中添加了一个编辑,解释了可能的解决方案。