Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve HTML5 data-* Attributes using C#

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?

like image 809
Arti Avatar asked Feb 23 '15 10:02

Arti


People also ask

How do I access data attributes?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5" .

Can data -* attribute contain HTML tags?

The data-* attribute is a Global Attribute, and can be used on any HTML element.

How do you get all elements with a data attribute?

To get all DOM elements by a data attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[data-id]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.

How get value of data attribute in CSS?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.


1 Answers

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

like image 88
alainlompo Avatar answered Oct 12 '22 23:10

alainlompo