I have a div in an asp.net master page with runat=server.
What I want to do is from codebehind when the user clicks on the div redirect to another page. I’ve tried the following:
HTML:
<div id="logoHead" runat="server"></div>
Code behind:
logoHead.Attributes.Add("OnClick", "window.location = MyUrl");
This doesnt work, how can I do this?
What you are doing will work just fine. The problem you have is the ‘Attributes.Add’ is causing the javascript to get HTML encoded. This is because you are not using an ASP.NET specific control. Your
onclickis rendering as:To get around this I place any javascript that I want to add, to a NON ASP.NET control in this manner, in a function to eliminate any funny characters that will be HTML encoded. Example:
Javascript:
ASPX:
Code behind:
This is only a problem with HTML controls that you are adding a
runat='server'tag to access them server side. If you switch yourdivto aasp:Panelthen there is no HTML encoding done on theAttribute.Addand you can just put whatever you want in there without the proxy javascript function. This is a kind of an annoying ‘feature’ but I suspect it is intended.