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

时间:2015-06-16 13:07:38

标签: ajax asp.net-mvc asp.net-ajax asp.net-mvc-partialview ajax.beginform

我使用弹出窗口创建新记录,然后在窗口内呈现view。除此之外,我根据其中组合框的selectedindex在此视图中调用partialview。我可以成功地将表单发布到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>

1 个答案:

答案 0 :(得分:2)

在这种情况下,您需要在没有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>

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