Rendering a partial view with jquery

2019-07-31 15:44发布

问题:

The problem;

I have a view with two partial views one view to handle client side msgs and a gridview.

the gridview is a form and can delete update items. When deleting or updating error/success msgs are generated in tempdata however only the grid partialview is being rendered from the actionresult functions.

I need a way to simply render the messages partial view without posting anything or redirecting it to the controller since the data already exists in tempData.

View:

<div id="page-KnownRecipient">   

    @Html.Partial("ClientSideMessages")

    @Html.Partial("_TabsPartial")

    @if(Model != null)
    {
        using (Html.BeginForm())
        {
            @Html.Partial("_EditModePartial", Model);//Grid
        }
    }

</div>

All callback routing from the gridview just returns partialview EditModePartial and since the VIEW is never reloaded the messages that should be displayed in "ClientSideMessages" partial is never rendered after delete/ update callbacks. So accordingly I need a way to render the "ClientSideMessages" partialview using jquery, no new data is needed only the actual rendering of the partialview.

//---- Ended up using something like this;

View;

    <div id="detailsDiv">
        @Html.Partial("ClientSideMessages")
    </div>

Controller;

public ActionResult StatusMessages()
{
    return PartialView("ClientSideMessages");
}

JS;

function getStatusMessages() {
    var sURL = "/Home/StatusMessages"; // Just put the function in some base controller
    var $detailDiv = $('#detailsDiv');

    $.get(sURL, function (data) {
        $detailDiv.html(data);
    });
}

Thanks for tips and pointers tho !

回答1:

If You only want to render

@Html.Partial("ClientSideMessages")

using Jquery You can :

<div id="target">
    @Html.Partial("ClientSideMessages")
</div id="target">

and use ajax:

$.ajax({
        url: "/{Controle}/ClientSideMessages",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: {Your data},
        error: function (data) {
            {error message};
        },
        success: function (data) {
                $('#target').html(data); // loading partialView into div
        }
    });


回答2:

To do this you have to create one Action at your Controller which will just return the Client Message Partial View. Once you do that you have to do the following.

<div id="page-KnownRecipient">   

    <div id="clientMessages">
    @Html.Partial("ClientSideMessages")
    </div>
    @Html.Partial("_TabsPartial")

    @if(Model != null)
    {
        using (Html.BeginForm())
        {
            @Html.Partial("_EditModePartial", Model);//Grid
        }
    }

</div>

And then you can use following function to render client message in any callback.

<script type="text/javascript>
$(function(){
   var renderClientMessage = function(){
   $("#clientMessages").load("ClientMessageAction_URL");
};
});
</script>