简体   繁体   中英

How do I load a view and then a partial view within it in a MVC project using javascript?

Whatever I do, I keep getting the reverse order. I just want to refresh the entire page after ajax finishes a certain action and then simply load a certain partial view, this is my attempt:

$.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("DeleteSensor", "PredefinedViews")',
                    data: JSON.stringify({ pviID: PredefineViewsItemID, pID: PredefineViewID }),
                    dataType: "json",
                    complete: function (result) {
                        location.reload(true);
                    },
                    success: function (result) {;
                        var urlShowSensors = "@Url.Action("ShowSensorNames", "PredefinedViews", new { predefinedViewID = "PredefID" })";
                        urlShowSensors = urlShowSensors.replace("PredefID", PredefineViewID);
                        $(divSensorNames).load(urlShowSensors);

In the debug I see that it successfully loads the partial view, but then it ends up doing the location.reload(true); LASTLY which in turn leaves me with an open view without an open partial view. Is there a way I can FIRST make it do location.reload(true); and THEN load my partial view?

UPDATE! It appears I never put a document.ready in my script tags, here is my entire script:

<script type="text/javascript">
    $(function () {
        $(".sensor-delete-table").on("click", function () {
            var divSensorNames = $("#sensorNames");
            var tr = $(this).parents('tr:first');
            var PredefineViewsItemID = tr.find("#PredefineViewsItemID").html();
            var PredefineViewID = tr.find("#PredefineViewID").html();
            var amount = parseInt($("[data-id='" + PredefineViewID + "']").text());
            var flag = confirm('@Html.Localize("deleteCheck")');
            var urlShowNewSensors = "@Url.Action("ShowSensorNames", "PredefinedViews", new { predefinedViewID = "PredefineViewID" })";
            urlShowNewSensors = urlShowNewSensors.replace("PredefineViewID", PredefineViewID);
            if (PredefineViewID != "" && flag) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("DeleteSensor", "PredefinedViews")',
                    data: JSON.stringify({ pviID: PredefineViewsItemID, pID: PredefineViewID }),
                    dataType: "json",
                    success: function (result) {
                        location.reload(true);
                    },
                    complete: function (result) {

                        var urlShowSensors = "@Url.Action("ShowSensorNames", "PredefinedViews", new { predefinedViewID = "PredefID" })";
                        urlShowSensors = urlShowSensors.replace("PredefID", PredefineViewID);
                        $(divSensorNames).load(urlShowSensors);
                    },

                });
            }
        });
    });
</script>

I thought I could do it like that, so can anyone correct my code here? Basically when i click a button, it deletes a row in a table in my partial view and it goes to a controller where it deletes the record from the data base. Now if everything went accordingly I want to refresh a table in my main view which is why I insist on doing a location.reload and then I want to load my partial view, which is why i need an url to be loaded on a certain div.

Load the partial view in document.ready function

and put the location.reload() in success block

       $(document).ready(function()
       {
           var urlShowSensors = "@Url.Action("ShowSensorNames", "PredefinedViews",
                        new {                 predefinedViewID = "PredefID" })";
                    urlShowSensors = urlShowSensors.replace("PredefID",  
                                                PredefineViewID);
                    $(divSensorNames).load(urlShowSensors);
       });


       $(".sensor-delete-table").on("click", function () {
       $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("DeleteSensor", "PredefinedViews")',
                data: JSON.stringify({ pviID: PredefineViewsItemID, pID: PredefineViewID
                    }   ),
                dataType: "json",
                success: function (result) {
                             location.reload(true);}});
       });

it is doing exactly what you have coded.

complete and success callbacks that you have overridden gets called on your call to @Url.Action("DeleteSensor", "PredefinedViews") . so you are left out with a view as if the user has gone to the page for the first time. There's no point of loading the partial view in the success callback as the whole page got reloaded in the complete callback .

As far as I can understand by looking at your code, you should call whatever in the success callback within the document ready .

$(function(){
    var urlShowSensors = "@Url.Action("ShowSensorNames", "PredefinedViews", new { predefinedViewID = "PredefID" })";
    urlShowSensors = urlShowSensors.replace("PredefID", PredefineViewID);
    $(divSensorNames).load(urlShowSensors);
});

Not sure what conditions you have to check. but it doesn't seem that you are using the response from the ajax call within the success callback . so the above should work.

UPDATE To answer your update

As you are already using partial views and as it seem you understand the concept of it, why don't you move the table to a partial view as well and call it just like you are trying to load ShowSensorNames partial and comment out the location.reload(true); code.

First create a partial view (eg call it MyTable.cshtml) and move your table html to it and strongly type it with the Model.

now in your View where the Table used to be. Do the following

<div id="myTableContainer">
    @Html.Partial("MyTable", Model)
</div>

Now create a action in your controller called MyTable which returns a partial view

public ActionResult MyTable()
{    
    var myTableDataModel = //retrieve table data

    return PartialView(myTableDataModel);
}

Now lets get to the javascript code

<script type="text/javascript">
$(function () {
    $(".sensor-delete-table").on("click", function () {
        var divSensorNames = $("#sensorNames");
        var tr = $(this).parents('tr:first');
        var PredefineViewsItemID = tr.find("#PredefineViewsItemID").html();
        var PredefineViewID = tr.find("#PredefineViewID").html();
        var amount = parseInt($("[data-id='" + PredefineViewID + "']").text());
        var flag = confirm('@Html.Localize("deleteCheck")');
        var urlShowNewSensors = "@Url.Action("ShowSensorNames", "PredefinedViews", new { predefinedViewID = "PredefineViewID" })";
        urlShowNewSensors = urlShowNewSensors.replace("PredefineViewID", PredefineViewID);
        if (PredefineViewID != "" && flag) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("DeleteSensor", "PredefinedViews")',
                data: JSON.stringify({ pviID: PredefineViewsItemID, pID: PredefineViewID }),
                dataType: "json",
                success: function (result) {
                    ///location.reload(true);
                },
                complete: function (result) {

                    var urlShowSensors = '@Url.Action("ShowSensorNames", "PredefinedViews", new { predefinedViewID = "PredefID" })';
                    var urlMyTable = '@Url.Action("MyTable", "PredefinedViews")';
                    urlShowSensors = urlShowSensors.replace("PredefID", PredefineViewID);
                    $(divSensorNames).load(urlShowSensors);
                    $("#myTableContainer").load(urlMyTable);
                },

            });
        }
    });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM