How can I add a random number to an ASP.NET menu item url on each click
One step to prevent caching (in addition to adding the appropriate headers etc..) is to add a random number to the end of my URLs.
I'm using an ASP.NET menu and would like to add a random number to each menu item's navigate URL as it is clicked.
I can do this in the MenuItemDataBound event, but haven't had much luck doing the same with the MenuItemClicked Event.
Answer (can't answer my own question for 8 hours, and I don't have time to wait that long so here's my server side solution.)
To do this server side, I've had to remove the sitemap and the databinding from the menu.
I simply added all of the items from the sitemap as menuitems to the items collection in the menu markup removing the url property. The key here is removing the url property.
<asp:menu&g开发者_C百科t;
<items>
<asp:menuitem Text="Home" ToolTip="Go Home" Selectable="True" />
</items>
</asp:menu>
Then in your code behind you can handle the MenuItemClicked event (which should now fire, because there is no longer a navigateurl in the markup).
In the MenuItemClicked event codebehind I simply do the following:
string TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
// get iframe control - must have 'runat=server' attribute
HTMLControl display = CType(this.FindControl("display"), HTMLControl);
// dispatch menuitem
switch (e.item.valuepath)
{
case "Home":
display.attributes("src") = "home.aspx?=" + TimeStamp()
break;
.
.
.
}
This is the server side solution with an iframe.
I don't know if you're considering client-side URL manipulation as an option, but running this little bit of JavaScript on each page load would give you the behavior you're looking for by appending a timestamp to each of the links. You can modify it to target links in a specific area/div of the site, but this example will change them all:
<!-- include the jQuery library -->
<script type="text/javascript">
$(function(){
var time = new Date().getTime();
$('a').each(function() {
var append = (this.href.indexOf('?') > -1 ? '&' : '?');
$(this).attr('href', this.href + append + 't=' + time.toString());
});
});
</script>
Since every time the page loads the timestamp will be different, you should always get a unique set of links.
EDIT Here's a working jsFiddle demoing the behavior: http://jsfiddle.net/2HzqU/2/
I don't think that's the best solution. Have you tried using something like this:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
精彩评论