简体   繁体   中英

How can I get the value of an attribute from code behind?

I have a checkbox which is responsible for showing/hiding a div. I created a custom attribute 'myDiv' and put the name of the div which the checkbox is responsible for there.

<asp:CheckBox ID="CheckBox1" myDiv="divRegisteration" myText=" הרשמה - " runat="server" AutoPostBack="true" Font-Size="18px" Font-Bold="true" Text=" הרשמה - הצג" OnCheckedChanged="CheckBox_CheckedChanged"/>

When I try to get the name of the div from the code behind, I get an error:

 protected void CheckBox_CheckedChanged(object sender, EventArgs e)
    {
        if (((CheckBox)(sender)).Checked==true)
        {
            CheckBox chk = (CheckBox)(sender);            
            object div = chk.Parent.FindControl(chk.Attributes["myDiv"]);

it does not find the attribute "myDiv". for some reason it only finds 2 attributes which I dont even know where they came from. Is there another way to get a custom attribute?

You can only set attributes to render at client side, it is not possible to directly access the attribute value (at server side) when from is POSTED . To access the attribute value, you can use hidden field which can be set at client side through javascript.

You can do that by using jquery

if ($('#CheckBox1').is(':checked')) {

    $("#Urdiv").show();
} else {
    $("#Urdiv").hide();
} 

use clientId at CheckBox1

Yes, you can get the value of an attribute from code behind. For example, if you have a checkbox control like this:

<input type="checkbox" runat="server" id="chkBoxCreate" class="item" itemid="1" onclick="Create();" />

then you can get it's value in code behind like below:

string itemId = chkBoxCreate.Attributes["itemid"];

Enjoy :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM