Skip to content Skip to sidebar Skip to footer

Div Adding Redirect And Background Image From Code Behind In Asp.net

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: H

Solution 1:

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 onclick is rendering as:

onclick="window.location='MyUrl'"

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:

functionredirect(address) {
    window.location = 'http://' + address;
}

ASPX:

<div id="divTesting" runat="server">
    Testing
</div>

Code behind:

divTesting.Attributes.Add("onclick", "redirect('www.microsoft.com');");

This is only a problem with HTML controls that you are adding a runat='server' tag to access them server side. If you switch your div to a asp:Panel then there is no HTML encoding done on the Attribute.Add and 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.

Post a Comment for "Div Adding Redirect And Background Image From Code Behind In Asp.net"