开发者

Adding class attribute from code behind

开发者 https://www.devze.com 2023-04-09 07:35 出处:网络
I have the following code: div1.Attributes.Add(\"class\", \"displayNone\"); it works on page load but doesn\'t on an OnClick event.

I have the following code:

div1.Attributes.Add("class", "displayNone");

it works on page load but doesn't on an OnClick event.

This is because my html <div id="div1"></div> seems to change to:

开发者_Python百科<div id="div1_ucSomeControl_SoemthingElse"></div>

after the page has been rendered.

How can I get around this?


I don't think that the ID of the control matters in this case. You may be running into this issue because the class attribute already exists. Try this instead:

div1.Attributes["class"] = "displayNone";


<div id="div1" runat ="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>

code behind:

protected void Button1_Click(object sender, EventArgs e)
{
    div1.Attributes.Add("class", "displayNone");
}

this will be work.


Normally you should do this kind of attributes manupilation/addition in the Page_PreRender event:

div1.Attributes.Add("class", "displayNone");

anyway when you say it does not work in the OnClick event you still meant Server side I guess; because on client side you cannot execute that code in that way.

Server side, usage of the object by id like div1 should always work, in codebehind objects's ids are not changed through the page life cycle.

0

精彩评论

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