📜 ⬆️ ⬇️

ASP.NET: CssClass as an alternative to client ID

In ASP.NET, it is rather difficult to predict the client ID of an element, that is, if you can specify the server control ID <asp:TextBox /> , then it is rather difficult to predict what the ID of the corresponding <input type=”text” /> element will be. While quite often you need to know the ID of the rendered item. But it looks something like this - ctl00_contentBody_txtStreet. There are several ways to overcome this difficulty, which are described here . All of them either require writing bulky constructions, or even creating their own controls. But there is another very simple way to get a client ID.

Surely, you all remember the CssClass attribute in ASP.NET server controls, which correspond to the class attribute HTML tags. Surely, many have worked with jQuery and know the selector that allows you to get elements with the specified class name. So why not combine all this?

And all together it will look like this:

<asp:TextBox ID="txtStreet" runat="server" CssClass="txtStreet" />

You simply give the CssClass property a unique value.
')
And then you can already get the entered value using javascript

alert($('.txtStreet').val());

Very simple. But it is worth remembering that this selector will iterate over all HTML tags, which in the case of a large page, may take some time. Therefore, you should specify jQuery in which tags it should look for, and this is done simply - you just need to add the tag name in front of the class selector:

alert($('input.txtStreet').val());

In ASP.NET 4.0, you don’t have to pervert so much, since client IDs will be more predictable.

Source: https://habr.com/ru/post/53347/


All Articles