[RESOLVED]Table in partial view being replaced with table containing old non-current data

I have a view which we will call Create.cshtml.  On this view there is a call to a partial view called _PurchaseRequestTable.cshtml, using RenderAction, which calls a separate action on the controller called PurchaseRequestTable which returns a partial view.

Now I have two buttons on the form one for creating the record in the database and the other for updating the record on the databases.  Now when the onclick event handler for the each button runs, first an Ajax call is made to a function to interact with
the database, and then an Ajax call is made to the PurchaseRequestTable action to rebuild the partial view and replace the contents of the div rendered in the partial view with the new return from the action.

However what is happenning is that when the buttons are clicked, the new data is properly saved to the database, but when the partial view is replaced in it showing the old data.

Here is the code for the RenderAction and the controller action

@using (Html.BeginForm(null,null, FormMethod.Post, new { id = "PRCreate" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Add Purchase Requests</legend>
        <div id="overlay" style="position: fixed;top: 0;right: 0;bottom: 0;left: 0;height: 100%;width: 100%;margin: 0;padding: 0;background: #000000;opacity: .15;filter: alpha(opacity=15);-moz-opacity: .15;z-index: 101;display: none;" >

        </div>


        @{ Int32 prID = 0;
            if (Model.PurchaseRequest != null)
            {
                prID = Model.PurchaseRequest.PRID;
            }
            Html.RenderAction("PurchaseRequestTable", new { id = prID });
           }
 
        <br />
        <br />
        <br />
                          ....
        public ActionResult PurchaseRequestTable(Int32 id = 0)
        {
            using (var db = new VFS_ProcurementTrackEntities(Session["csProcTrack"].ToString()))  //breakpoint added here*****
            {
                ViewBag.PRID = id;
                var PR = new PurchaseRequestTableModel();



                if (id != 0)
                {
                    var currentRequest = db.prc_PRs.Find(id);
                    PR.PurchaseRequest = currentRequest;

                }
                else
                {
                    DateTime value = DateTime.Today; // Convert.ToDateTime("01/01/" + DateTime.Today.Year.ToString());
                    PR.PurchaseRequest = new prc_PRs();
                    PR.PurchaseRequest.PRID = 0;
                    PR.PurchaseRequest.PROriginatorUserRecID = (int)Session["UserRecID"];
                    PR.PurchaseRequest.PRDateCreated = value;
                }

                int defaultValue = (int)Session["UserRecID"];
                var AMSList = db.AMSList_get(0).ToList();
                SelectList amsDDList = new SelectList(AMSList, "AMSID", "AMS" , id == 0 ? defaultValue : PR.PurchaseRequest.PROriginatorUserRecID);


                PR.DDAMS = amsDDList;
                return PartialView("_PurchaseRequestTable", PR);
            }
        }

And here is the code for one of the click events being called.

   $(function () {
        //alert("created function");
        var UpdatePRs = function () {
            //alert("called function");
            //debugger
            var sURL = '@Url.Action("UpdatePurchaseRequest", "AJAXFunctions")';
            var goURLid = $("#PurchaseRequest_PRID").val();
            var form = $("#PRCreate");
            var bError = false;
            var returnedInfo = '';
            var sResultMessage = '';

            //alert(options.url);
            $.ajax({
                url: sURL,
                type: 'POST',
                data: form.serialize(),
                cache: false,
                async: false,
                dataType: 'json',
                //contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    ////debugger
                    if (data != null) {
                        $(data).each(function () {
                            returnedInfo = data;
                        });
                    }
                    else {
                        returnedInfo = "Nothing was returned";
                        bError = true;
                    }
                },
                error: function () {
                    sResultMessage = 'An Error has occurred, and the changes to the PR Information were not saved.';
                    bError = true;
                }
            });
            //debugger
            //if (!bError) {
            var sURLRepost = '/PR/PurchaseRequestTable' + '/' + goURLid;
            //var options = 
            //};
            //alert(options.url);
            $.ajax({
                url: sURLRepost,
                type: "get",
                async: false,
                dataType:"html",
                success: function (data) {
                    //debugger
                    if (data != null) {
    //this is where the ajax call returns information showing the data prior to being changed. 
//break point in action is not hit. $("#PRtableView").replaceWith(data); } else { sResultMessage = "An Error has occured and no information was returned"; } }, error: function () { sResultMessage = 'An Error has occurred, and no data returned'; } }); if (!bError) { sResultMessage = "Your Edit has been completed. The changes were saved to the database."; $("#PRCreated").text(sResultMessage).toggle(); } else { sResultMessage = "Your edit was not completed. " + returnedInfo; $("#PRCreated").text(sResultMessage).toggle(); } }; $('#btnEditPR').on('click', UpdatePRs); });

On another thread with a similar problem where the Aijax call was returning a cached version of the action result Starain chen had me add a decoration to the Action like this:

 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Index(int id = 0)
        {
            if (!Request.IsAjaxRequest())
            {
                id = (int)Session["UserRecID"];
            }
             ViewBag.UserID = (int)Session["UserRecID"];
             using (var db = new VFS_ProcurementTrackEntities(Session["csProcTrack"].ToString()))
             {
             //var db = new VFS_ProcurementTrackEntities(Session["csProcTrack"].ToString());
                 var model = (from pr in db.PurchaseRequests_Get_All(id)
                             orderby pr.PR_Number descending
                             select pr).ToList();
                 if (Request.IsAjaxRequest())
                 {
                     return PartialView("_PurchaseRequestsGrid", model);
                 }

                 return View(model);
             }
        }

And that resolved all of my issues.  However when I tried to do the same for the offending action here first I got "Duration must be a positive number and then when I arbitarily set it to 1 then it said that you could not use the parameter "NoStore = true"
on a on a child action.

At this point I was baffled, and asked for advice and it was suggested I start a new thread here.

So if anyone has any ideas then please let me know.

joeller

However what is happenning is that when the buttons are clicked, the new data is properly saved to the database, but when the partial view is replaced in it showing the old data.

Hi joeller,

Thanks for your post.

With your description and code provided, I see you want to update records with ajax call update action.

Then update the UI with ajax call the partial view render action. For the second ajax request always the old

content returned to, I think is the cache caused your problem. Please disable the cache of the second ajax like below:

 
            $.ajax({
                url: sURLRepost,
                type: "get",
                async: false,
                cache: false, 
                dataType:"html",
                success: function (data) {
                   
                  ................

Hope this helps, thanks.

Best Regards!

Fuxiang Zhang – MSFT

Please disable the cache of the second ajax like below:

OK that did it.  as the OP stated I tried to do that with an attribute added to the server side function but was not able to.  It totally slipped my mind that thiscould be done client side.

Thanks loads.  This wa driving me crazy.

Leave a Reply