How to retrieve HTML5 data-* Attributes using C#
Asked Answered
B

1

10

I have a asp checkbox in my form:

<asp:CheckBox id="option" runat="server" OnCheckedChanged="checkChange" data-attributeA="somevalue1" data-attributeB="somevalue2" AutoPostBack="true" />`

In my OnCheckedChanged event I want to retrieve these two data-attributes.

protected void checkChange(object sender, EventArgs e) {}

How do I do that?

Brahmana answered 23/2, 2015 at 10:40 Comment(1)
possible duplicate of How can I access custom Textbox attributes in ASP.Net?Sherillsherilyn
H
13

The same approach in the link shared by @musefan will work for you.

I have created a CheckBox:

<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" dataAttributeA="Test Custom Attr A" dataAttributeB="Test Custom B" Text="Check it or dont" AutoPostBack="True" />

Then a method to handle the changed event:

 protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        String customAttr1 = CheckBox1.Attributes["dataAttributeA"].ToString();
        String customAttr2 = CheckBox1.Attributes["dataAttributeB"].ToString();

        Response.Write("<h1> Custom Attributes A and B = " + customAttr1 + " " + customAttr2);

    }

And finally I have set the AutoPostBack property of the CheckBox to true, so It's change event will be triggered as soon as it's clicked.

I have obtained the expected result

Custom Attributes A and B = Test Custom Attr A Test Custom B

Headgear answered 23/2, 2015 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.