Search code examples
c#asp.net-mvcpartial-viewsjquery-load

jQuery.load() on an MVC 3 partial view only calls the server once (not a rebind issue)


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");
        }
    }
}

Solution

  • 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 ()
    {
        ...
    }