簡體   English   中英

動態創建的Partial View不會在提交時調用控制器操作

[英]Dynamically created Partial View does not call controller action on submit

我正在使用AJAX用這樣的局部視圖替換引導程序模式內容:

主視圖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函數來獲取局部視圖以調用create action控制器:

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

那么,為什么的原因create controller action從未引用,是因為submit的事件bindForm從未被執行的功能。 如我所發現的, bindForm函數中的dialog selector阻止了事件的觸發。 我已在問題中添加了編輯內容,以解釋可能的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM