Selecting by ID attribute using JQuery in ASP.NET - asp.net

I've just started using JQuery in VS 2008, and so far I like it! But, I'm confused about how I should be using JQuery in order to select asp.net controls on a webpage.
For example, I have the following code (just a mock-up):
<asp:textbox id="txtSomeData1" runat="server" text="Some Data!!"></textbox>
Now, if I want to use JQuery to select the textbox and change it's text to "Some More Data!!", then I would have to do something like:
$('input#ctl00_ContentPlaceHolder1_txtSomeData1').val('Some More Data!!');
Which, quite frankly, is annoying because I don't want to mess with having to figure out what the id of the control is after it's rendered to the webpage (ctl00_ContextPlaceHolder... blah blah blah).
Is there a way that I can select the textbox without having to use the id of it? Also, I know that you can select by class name, but that doesn't help much if the control that you're selecting doesn't have a class.
Am I just missing something here?
JUST TO REITERATE: I do not want to use a class to select the input tag!! I would like to use the id "txtSomeData1" and not the long id that is rendered to the webpage.

What you want to do is either:
$("input[id$='_txtSomeData1']").val().....
or you could add a class or custom attribute to the textbox that you can select on

if the javascript is on the same .aspx file, you can do:
$('<%= txtSomeData1.ClientID %>').val('Some More Data!!');

This is a big complaint the community has with ASP.Net web forms. In ASP.Net 4.0 you get control of your IDs back so it's like you're wrote it in raw HTML. Alternatively, without .Net 4.0, you could use ASP.Net MVC which, for the most part, doesn't use server controls, so you wouldn't have the issue.
But like happytime harry says, adding a class may be want you want if you're working with web forms and jquery.

If you are going to externalise the JavaScript to its own .js file you are stuck with either hard coding in the id (most efficient), some regular expression selector or using the inefficient by class name selector.
However if it is in the same file as the .NET control you could always use $('<%=txtSomeData1.ClientID %>')

There are lots of selectors to use... maybe adding a class is what you want to do.
http://docs.jquery.com/Selectors

jQuery Wildcard Selectors are what you may be missing here.

You can add 'marker' classes to any control whose sole purpose is for use in a jQuery selector.
That, along with navigating the tree heirarchy (something like "$(element).children('.myClass').show()" might be a good way to do this without IDs.
Btw, http://visualjquery.com/ is a great way to view the jQuery APIs etc.

You can use the element[id$=Identifier] notation, which looks for the id ending with the text you specify (it's the ID you specify in ASPX markup). Here is an example illustrating how you can use it (see slide #30): Building intranet applications with ASP.NET AJAX and jQuery.

Please use the following syntax :
$("[id*=txtSomeData1]") to reference any asp control

For ASP.NET Web Forms, you can use ClientIDMode="Static" to prevent the id from changing:
<div id="MySection" ClientIDMode="Static" runat="server"></div>
which means you can then reference the element in a separate plain JavaScript file if required, without having to embed the JavaScript in the .aspx file:
var mySection = document.getElementById("MySection");
and even add classes:
mySection.classList.add("hidden");
And the CSS used above for reference:
.hidden {
display: none !important;
}

Related

Is it bad to use runat="server" on <tr>?

I'm supporting an application that uses runat="server" all over the place to show/hide table rows.
For example, in places where there are dependent DropDownLists, the row with the child ddl will be hidden until a value us chosen in the parent ddl.
Is that a bad practice? Is there a better way to do this?
I use runat="server" anytime I need it. So I think you can use it too. :-)
I think that's absolutely terrible practice. First of all you do not need to make the trip to the server to hide and show controls, unless you need new data.
Second, any decent javascript framework will allow you to hide show controls based on the control's id, class name, or whatever css selector. Moreover using a javascript post/get to a generic handler will give you the data that you need without the postback.
I'd suggest using JQuery, or some other alternative.
It depends on how much you care about performance. Anything that is marked with runat="server" goes through more processing than just client side tags.
Personally, I've used them before. Especially in the situation where a table cell or table row is relying on data from the server. You can use Javascript or JQuery with a hidden field but you still have to hit the server for the hidden field, so it doesn't buy much.
It's not bad to use runat="server" with standard HTML controls. Often you'll find the use of PlaceHolders to show and hide content on pages, or in ASP.NET MVC you might see the use of inline code blocks such as <% ... %> within the views. On it's own and not in consideration of other design aspects, it's neither good nor bad.
That's what I do to hide the row containing other server controls. The other options are to use a asp:panel or other container, but that will add more HTML without any gain.
I don't think it's necessarily bad practice. I've done the very same thing plenty of times. I think it's mainly personal preference.
Not at all. ASP.NET supports making any html tag run on the server side. Your alternative is to wrap the tag in a Panel, and hide or show that. If you're not looking for the extra functionality or want to control the output yourself, making an html tag run on the server isn't a problem.

asp.net+css+jQuery - how does it all work together?

I would like to understand how can I use jQuery to work with asp.net and css.
When I'm writing asp.net code and for example I'm adding to a page DropDownList, I can't see it in the source when I'm opening source of a page in web browser. Instead of dropdownlist I can see select tag. When does the "magic" is done to change asp.net tag to select?
What is more I can't see my CSS classes names added to asp.net tags. There are some kind of differen CSS class names. But when I'm opening developer tools in IE, I can see CSS class names, which are same as in my definition.
And the last thing. What names of a tags sould I use in jQuery to traverse page which was developed in asp.net. Shoud I use a tags which I see in the source code of a page in a browser or can I ask jQuery about asp.net tags? What about CSS classes? Why I can't see them in a source of a page in a browser? Can use my names of a CCS classes under jQuery queries?
Please, can anybody explain me how does this three technologies work together?
When does the "magic" is done to change asp.net tag to select?
Most of "magic" you're wondering about is done by ASP.NET controls, which are designed to generate the markup that is sent to the browser.
When a request is received, the application iterates over each control, calling its Render method (inherited from the Control class), which allows each control to generate the markup they represent.
Following your example, the DropDownList control generates a <select> tag. As a ListControl, it uses the ListItem controls to create the <option> tags within.
Another would be the GridView, which generates a <table> using GridViewRow controls for <tr> and various HTML Controls, such as TableCell for <td> and <th>, to create the rest of the markup.
Shoud I use a tags which I see in the source code of a page in a browser or can I ask jQuery about asp.net tags?
No, jQuery/JavaScript have no knowledge of server-side control names, only the markup they generate. So, rather than searching for $('DropDownList'), you'd search for $('select').
What is more I can't see my CSS classes names added to asp.net tags. There are some kind of differen CSS class names.
By "CSS Names," do you mean IDs? I'm sorry to ask, but CssClass attributes shouldn't change in value from server-side to client-side, just in name -- CssClass to just class.
IDs, on the other hand, are prefixed to ensure their uniqueness throughout the page, including a prefix of the MasterPage and ContentPlaceHolder names, if they're used. For this reason, I'd steer away from trying to use IDs to apply CSS to server-side controls, using classes instead.
Now, the end of the ID should remain as the ID you gave in server-side, so you should still be able to find the element in jQuery using the Attribute Ends With Selector [name$='value']:
# ASP
<asp:DropDownList ID="AnyGivenDropDown" runat="server" />
# HTML (generated)
<select id="ctl00_PageContents_AnyGivenDropDown"></select>
# JavaScript
$('select[id$="_AnyGivenDropDown"]');
Otherwise, I'd stick to classes to find the controls you're looking for:
# ASP
<asp:DropDownList ID="AnyGivenDropDown" CssClass="anygiven" runat="server" />
# HTML (generated)
<select id="ctl00_PageContents_AnyGivenDropDown" class="anygiven"></select>
# JavaScript
$('select.anygiven');
# CSS
.anygiven { }
The "magic" happens in the render event of the asp.net page lifecycle. Asp.net server controls all render as standard html element(s). The most important difference is that you can access them and their values on the server side. WebControls also have a CssClass property that when rendered becomes the class attribute of the HTML element.
The id can be a bit tricky when working with jQuery and CSS. This is because depending on the controls hierarchy they may have a clientID such as ctl100_containerID_myControl instead of myControl. To overcome this in jQuery when you reference a control you can refrence it by its ClientID like so:
$('#<%=myControlID.ClientID%>')
This is serverside that will write the client side ID of the control after it is rendered.
ASP.NET: High-level web development framework. When you create a web form in .NET, the framework will work together with the IIS handlers and create (hopefully) valid HTML that will work with your server-side code during postbacks.
JQUERY: This will allow you to perform client-side scripting such as calculation, validation, and most notably AJAX, etc. This is basically just a wrapper for a simpler and easier-to-read version of javascript.
CSS: Takes the HTML and makes it pretty.
All three technologies work very well together if you know what you're doing.
I'm not sure if that's what you're looking for, but it sounds like you might want to invest in some beginner's literature.

ASP.NET - What is the best way to keep jquery from cluttering up my ASPX files?

I'm starting to use more and more jquery. I'm working with dialogs, and each dialog (including javascript) is taking upwards of 20-30 lines of code. There's a few pages where I'll have over 5 dialogs. This gets ugly fast. I haven't even begun to get into sliding interfaces or calendar controls yet.
I have more of a PHP background... and in these situations i'd be moving things to an "include" file. I can see that working for items such as jquery-dialogs in ASP.NET, but when I start adding jquery features to actual ASP.NET form items.. that won't be an option (as far as I know).
How can I keep the extra javascript and extra floating divs from cluttering up my ASPX files too bad?
I'm prepared to partition the ASPX file into well documented, distinct sections... this just results in a very "tall" file. Any better solutions?
Thanks.
You could put the javascript code into separate js file(s). You then reference the js file(s) in your page.
I'm not sure how you're structuring your .NET and your markup, but I'd be using external JavaScript files to handle all of that, no inline JavaScript. That's how we work in here, and no issues so far, with a nice separation of markup, CSS, JavaScript, and .NET.
If you have specific types of dialogs, then use classnames on your markup, then in the JavaScript include files use classes as your selectors to create the dialogs.
Let's see...
Since you are using jQuery, you must know the script src syntax already to include javascript files, so I assume this is not the problem :).
For those pesky crazy looking control ID that ASP.NET create...
cache them in a JavaScript global variable at the end of the page... like:
<script>
ControlIDs = {
SaveButton = '<%=SaveButton.ClientID%>',
BlahTextBox = '<%=BlahTextBox.ClientID%>'
}
</script>
And in your separate jQuery code file, do...
$(ControlIDs.SaveButton).Whatever()
3. Instead of using the ASP.NET control ID, maybe you want to try using the CSS Class Name as selector in jQuery to get to a particular control (treat class name as control Id), might not be an ideal idea, but it could work.
Any of these should allow you to do some degree of Javascript separation.

Codebehind and inline on same page in ASP.NET?

In ASP.NET, is it possible to use both code behind and inline on the same page? I want to add some inline code that's related to the UI of the page, the reason to make it inline is to make it easy to modify as it outputs some HTML which is why I don't want to add it in the code behind, is this possible in ASP.NET?
Edit: I'm sorry, obviously my question wasn't very clear, what I meant is using a script block with runat="server", this is what I meant by inline code.
Thanks
Yes, you can use inline code just like in classic asp. You can use 'this' or 'me' to get to the code behind fields, methods, etc.
Yes, that will work, make sure the code behind class is declared as a partial class, which is the default these days anyway. Don't think it would work in 1 or 1.1

should every element with runat=server have an id attribute?

I have inherited an asp.net website to maintain
when looking at the aspx page, almost every element with runat=server don't have id attribute defined.
should I go through every element and add one?
Unless the control is inside a repeating control it should have a unique ID attribute assigned to it. Here is some MSDN documentation on how to add server controls to an ASPX page.
You only need to give them ids if you're going to reference them in your code. If you're not referencing them at all you might wonder why they are .net controls and not just html elements.
ASP will assign an unique ID if you don't. Sometimes I don't bother when I won't be manipulating it.
Speaking specifically to your situation of having inherited an app, it's not a pressing issue. ASP.NET will automatically generate IDs for them at runtime.
Generally, aiming to replace those controls with HTML elements (as someone else mentioned) is a good idea. Do be careful though. Just because an element doesn't have an ID doesn't mean it's not being referenced on the server side at runtime.
You don't need to set IDs to the controls you don't reference. ASP.NET will do it for you. That's it.
This does NOT automatically mean, they can be replaced with HTML controls. Having a control with runat="server" without having an ID set is perfectly reasonable.
e.g.:
<asp:ListView runat="server" DataSourceID="someDataSource">

Resources