On the site I’m developing, there is a page that lists all of the users on the site (and some other information) in a table. This page is identical to everyone who logs in (at any given time, at least), except for one difference – their own row is highlighted. So it seemed to me that this would be an ideal candidate for caching – we don’t need every user that hits that page to recalculate and render the data on the page when only that one thing changes.
I attempted to handle this by adding output caching to the page, and moving the highlighting of the table row to JavaScript (a jQuery call) – my hope was that this page would be cached, but the JavaScript would be run every time somebody hits it, resulting in their own row being highlighted. That doesn’t seem to be the case, however. If I hit the site first, my row is highlighted. Then, if somebody else hits the page within the cache expiry time (on a different machine, so it’s not a browser cache thing), they see the page with my row highlighted rather than their own, until the cache expires – and then everybody sees the row highlighted of whoever hit the page next, and so on. It seems like it is serving up the cached version of the page after the JavaScript has been executed, rather than serving up the cached version of the page and then running the JavaScript.
Is there a way to do what I’m trying to do – cache the page so I’m not executing ASP.NET calls every time somebody hits the page, but have the JavaScript run fresh every time the page is loaded so a different row gets highlighted? Or if not with JavaScript is there any way to do this? I thought about using setInterval to do the check for a highlight (and re-highlight the proper row) at regular intervals, but that seems like overkill since this only needs to be done once after the page is loaded, and never done again until the page is reloaded.
Here are the relevant parts of my aspx file:
<%@ OutputCache Duration="60" VaryByParam="none" %>
<script type="text/javascript">
jQuery(document).ready(function($) {
var isAuthenticated = ('<%= Context.User.Identity.IsAuthenticated %>' == 'True');
if (isAuthenticated) {
var owner = '<%= Context.User.Identity.Name %>';
$('#' + owner).css("background-color", "#bdf");
}
});
</script>
<table>
<tr>
<th>
Owner
</th>
...
</tr>
<% foreach (var item in Model.Items) { %>
<%= String.Format("<tr id=\"{0}\">", item.Owner) %>
<td>
<%= Html.Encode(item.Owner) %>
</td>
...
</tr>
<% } %>
</table>
The page is cached after the values like
Context.User.Identity.IsAuthenticatedare evaluated. So even though the JavaScript is executed on the client, it already contains the specific values (your values) from the cache.To do this right, you can either