开发者

div adding redirect and background image from code behind in asp.net

I have a di开发者_JAVA技巧v 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 onclick is rendering as:

onclick="window.location=&#39;MyUrl&#39;"

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:

function redirect(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜