2

The following code shows 1 view, 1 partial view, and 1 controller. The view contains a button to get the current time and a partial view that displays that time. The button's click, wired through jQuery, calls $.load() on the partial view's container.

The first click on the button works perfectly, but no subsequent call gets to the server; the function fires, the load fires, but the server never gets the request.

Any ideas what the problem could be?

Index.cshtml

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>ContainerView</title>
    <script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $('#btnRefresh').click(function () {
                $("#divTime").load('@Url.Action("GetTime")');
            });
        });
    </script>
</head>
<body>
    <div>
        <input id="btnRefresh" type="button" value="Get Time"/>
        <div id="divTime">
            @Html.Partial("_Time")
        </div>
    </div>
</body>
</html>

_Time.cshtml

@ViewData["Time"]

ContainerController.cs

using System;
using System.Web.Mvc;

namespace PartialViewAjaxFormModel.Controllers
{
    public class ContainerController : Controller
    {
        //
        // GET: /Container/

        public ActionResult Index()
        {
            return View();
        }

        public PartialViewResult GetTime()
        {
            ViewData["Time"] = DateTime.Now.ToLongTimeString();

            return PartialView("_Time");
        }
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
denious
  • 163
  • 1
  • 11

1 Answers1

2

It's getting cached. I use an action attribute for this:

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted ( ActionExecutedContext context )
    {
        context.HttpContext.Response.Cache.SetCacheability( HttpCacheability.NoCache );
    }
}


[HttpGet]
[NoCache]
public JsonResult GetSomeStuff ()
{
    ...
}
asawyer
  • 17,642
  • 8
  • 59
  • 87
  • [OutputCache(Duration = 0)] also seems to work, is there a difference between the two? – denious Mar 22 '12 at 22:07
  • @denious Not sure off the top of my head. I'd consult MSDN. – asawyer Mar 22 '12 at 22:08
  • The difference appears to be that setting the Duration to 0 works as a hack and makes the cache instantly expire, whereas NoCache disables caching at the root. Just to be sure I also included `context.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0, 0, 0, 0));` in your attribute. Thanks again! – denious Mar 22 '12 at 22:18