简体   繁体   English

动态创建的Partial View不会在提交时调用控制器操作

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

I am using AJAX to replace bootstrap modal content with a partial view like this: 我正在使用AJAX用这样的局部视图替换引导程序模式内容:

Main View HTML 主视图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 主视图内的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;
    });
}

Partial View HTML 部分检视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: 但是,当我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);
    }

I tried placing a brake point next to ModelState.IsValid but it never gets hit.Also the browser console is not displaying any errors 我尝试在ModelState.IsValid旁边放置一个制动点,但它从未被击中,而且浏览器控制台未显示任何错误

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: 我设法通过将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;
    });
}

So the reason why the create controller action was never invoked, was because the submit event of the bindForm function was never being executed. 那么,为什么的原因create controller action从未引用,是因为submit的事件bindForm从未被执行的功能。 As i have discovered, the dialog selector in the bindForm function stopped the event from being triggered. 如我所发现的, bindForm函数中的dialog selector阻止了事件的触发。 I have added an edit to the question explaining a possible solution. 我已在问题中添加了编辑内容,以解释可能的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Ajax成功函数上的控制器中调用操作方法以渲染部分视图 - Call Action Method in controller on Ajax success function to Render partial view 提交后的Ajax调用未在Yii中调用正确的操作/控制器 - Ajax call after submit does not call the right action/controller in Yii Ajax操作URL到局部视图内的控制器 - Ajax action URL to a controller inside a partial view 使用Ajax调用在部分视图上提交 - Partial View on Submit using Ajax call Umbraco AJAX部分视图控制器操作调用-无法检索Umbraco.Context - Umbraco AJAX partial view controller action call - unable to retrieve the Umbraco.Context 如何在按下提交按钮时将整个模型对象从视图传递到jquery ajax调用的控制器动作? - How to pass whole model object from view to controller action from jquery ajax call on pressing submit button? 在jQuery中动态创建的表单未提交 - Forms created dynamically in jquery does not submit 当我使用$ .getJSON方法时,ASP.NET MVC部分视图不会调用我的操作 - ASP.NET MVC partial view does not call my Action when i used $.getJSON method 部分视图中的BeginForm不会触发控制器方法 - BeginForm in Partial View does not fire controller method 如何将值从控制器动作方法传递到局部视图 - How to pass value from controller action method to partial view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM