Why PartialView cannot reload with Ajax in MVC

1.8k views Asked by At

I use a popup window to create a new record and I render a view inside the window. In addition to this, I call a partialview in this view according to the selectedindex of a combobox in it. I can successfully post the form to the Controller and return it to the view when there is an error. However, after returning the form, only the view part returns and I cannot render the partialview. So, how can I also render partialview as the last status just before submitting the form?

View:

<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

There are 1 answers

6
Dion Dirza On BEST ANSWER

You need to do custom ajax post without HTML helper in this case. Create a normal form :

<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>

and do post by jquery similar like this

<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>

Hope this sample help you solve the problem.