简体   繁体   English

jQuery $ .post上的MVC 4 PartialViewResult缓存

[英]MVC 4 PartialViewResult caching on jQuery $.post

I have a jQuery $.post back to a MVC 4 Controller that will return back a PartialViewResult with rendered using the data sent in the POST. 我有一个jQuery $ .post返回到MVC 4控制器,它将返回使用在POST中发送的数据进行渲染的PartialViewResult。 When debugging the Partial View and Controller, the correct data is being received and sent to the Partial View as the View Model. 调试部分视图和控制器时,将接收正确的数据并将其作为视图模型发送到部分视图。 The issue is, when analyzing the HTML sent back in the AJAX result it is containing seemingly "cached" data from the original page refresh. 问题是,当分析在AJAX结果中发送回的HTML时,它包含来自原始页面刷新的看似“缓存”的数据。

I have seen a good amount of posts on here that are similar, but none that were the same as my issue. 我在这里看到了大量类似的帖子,但是都没有与我的问题相同。

I am aware that HTTP Post requests do not cache in the browser, so that is not the issue. 我知道HTTP Post请求不会缓存在浏览器中,所以这不是问题。 I also have set the set the OutputCache attribute to NoStore = true, etc. 我还设置了OutputCache属性为NoStore = true,等等。

Controller 控制者

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public partial class MyController : Controller
{ 
  ...
    [HttpPost]
    public virtual ActionResult UpdatePartial(MyViewModel myVm)
    {
        return this.PartialView("My/_Partial", myVm);
    }
}

JS JS

$('.someButton').click(function () {
        $.post(myAjaxUrl, $('form').serialize(), function (data) {
            $('#myContent').html(data);
        });
    });

I'm able to work around this by adding ModelState.Clear prior to doing any operations on the model. 我可以通过在模型上执行任何操作之前添加ModelState.Clear来解决此问题。

[HttpPost] 
public virtual ActionResult UpdatePartial(PersonViewModel model) 
{ 
    ModelState.Clear(); 
    model.FirstName += "1"; 
    model.LastName += "1"; 
    model.Age += 1; 
    return this.PartialView("../My/_Partial", model); 
}

This question has an answer by Tim Scott with more info an links. 这个问题有蒂姆·斯科特(Tim Scott)的答案,还有更多信息链接。

By default JQuery will cache $.ajax XMLHttpRequests (unless the data type is script or jsonp). 默认情况下,JQuery将缓存$ .ajax XMLHttpRequests(除非数据类型是script或jsonp)。 Since $.post is implemented via $.ajax, JQuery itself has cached your request. 由于$ .post是通过$ .ajax实现的,因此JQuery本身已缓存了您的请求。 The following JS should work. 以下JS应该可以使用。

JS JS

$('.someButton').click(function () {
    $.ajax{(
        url: myAjaxUrl,
        data: myAjaxUrl,
        success: function (data) {
           $('#myContent').html(data);
        },
        cache: false
    });
});

You might also find it worthwhile to handle the error event in case the post doesn't succeed. 如果发布失败,您可能还会发现值得处理错误事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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