小编典典

为什么PartialView无法在MVC中重新加载Ajax

ajax

我使用弹出窗口创建新记录,并view在窗口内部渲染。除此之外,我还partialview根据其中一个组合框的selectedindex在此视图中调用a
。我可以成功将表单发布到Controller并在出现错误时将其返回到视图。但是,返回表格后,只有view零件返回,而我无法渲染partialview。因此,partialview在提交表单之前,我又如何将其呈现为最后状态?

视图:

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>



<div id="target">

@using (Ajax.BeginForm("_Create", "Issue",
        new AjaxOptions
        {
            HttpMethod = "POST",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "target"
        }
        ))
{

    @Html.AntiForgeryToken()

    <div class="container">

        @Html.ValidationSummary(true)

        @Html.LabelFor(m => m.ProjectID)
        @(Html.Kendo().DropDownList())
        //... some stuff (removed for clarity)

        @*Render Partialview according to Dropdownlist's selectedIndex*@
        <!-- Place where you will insert your partial -->
        <div id="partialPlaceHolder" style="display:none;"></div>

    </div>

    <div class="modal-footer">
        @(Html.Kendo().Button()
                .Name("btnCancel")
        )
        @(Html.Kendo().Button()
            .Name("btnSubmit")
        )
    </div>
}

</div>


<script>

//Render Partialview according to Dropdownlist's selectedIndex
$('#ProjectID').change(function () { /* This is change event for your dropdownlist */

    /* Get the selected value of dropdownlist */
    var selectedID = $(this).val();

    /* Request the partial view with .get request. */
    $.get('/Issue/RenderPartialView/' + selectedID, function (data) {
        /* data is the pure html returned from action method, load it to your page */
        $('#partialPlaceHolder').html(data);            
    });

});

</script>

阅读 315

收藏
2020-07-26

共1个答案

小编典典

在这种情况下,您需要在没有HTML帮助程序的情况下进行自定义ajax发布。创建一个普通表格:

<form id="frmEdit" class="form">
    @Html.AntiForgeryToken()
    <div class="container">
        @Html.ValidationSummary(true)
        //.... rest form component
        <button id="btnSubmit" type="submit">Submit</button>
    </div>
</form>

并通过jquery像这样发布

<script>
$( "form" ).on( "submit", function( event ) {
    event.preventDefault();
    $.post(urlPost, $(this).serialize()).done(function(){
        // update your target id here and re-fetch your partial view
    }).fail(function() {
        // show error in validation summary
    });
});
</script>

希望此示例可以帮助您解决问题。

2020-07-26