possible to reference CSS selector in code-behind ASP.NET - asp.net

Let's say I have this HTML markup on an aspx page:
<div id = 'logo-container' class='foo'>
<img alt='logo' src ="images/foo.png" />
</div>
Pure html, not runat=server.
Is it possible, in aspx code-behind, to refer to a DOM element using CSS selectors? Could you get a reference to the IMG doing something like this:
foreach element in GetElement("#logo-container img")
{
do something with element, e.g. change a style attribute
}

No, you cannot, unfortunately. You'd be beter off doing it the intended way. If you need to access the controls in code-behind, just add the runat="server" attribute.
Why don't you want to run the controls at the server, considering that you need to access them in the code-behind? Are you worried about the auto-generated IDs? If so, you can resolve this by setting ClientIDMode to static.
If you do run the control at the server, you should be able to find the controls with that class using LINQ like this:
var ctrls = pnlControls.Controls.OfType<WebControl>().Where(i => i.CssClass == "logo-container");
Note: You can Replace WebControl with a more specific control if needed.

Short answer - No. If the control is not set to runat="server", you cannot access it from the code behind. However, you can access the element using Javascript and then call a server-side method to do whatever logic you want to do.

I feel better Solution is :
If you really want to change the style/css class you can better go for jquery and customize the way you want it.

Related

How to access non-asp <img> tag from code behind?

We're working on a big project and we're stuck a bit here.
I need to access the <img>'s from an .ASPX from the code-behind on the PageLoad()
to assign the right image (attrib src) depending on the value we just collected from the DB from an SQL Query.
We can't use the runat="server" attribute to see it server side because we got a bunch of jQuery using the img name tag to work with.
I'm sure there's a way to access and modify the src attribute of the images from the code behind view?
You can use a Literal control to output the image element.
You can access the value of the literal to extract (parse out) any information from it and re-write it.
You can use the ClientIdMode=Static property on your image tag. That way you can add the runat=server attribute and you can still access the image tag from your jquery.
Check the following documentation for more info.
To set the src attribute you will have to re-render the control or manipulate by emitting JavaScript.

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.

Using Javascript (DOM) with ASP.NET

I have an asp.net page with several list boxes.
I would like to include some javascript on the page that allows a user to drag individual list elements from one box to another.
On a normal web page, the script to do this is reasonably simple, however, with the element IDs generated by ASP.NET, I don't know what identifiers to have my script look up?
Any thoughts on how to do something like this?
Add a identifying CSS class to your elements and use those. i.e. jQuery has a superb support for that so you can grab all elements and loop through them to do whatever you want.
Check out the ClientId property of the Control class.
Note: The ASP.NET ListBox control inherits from Control.
Update
In reponse to the comments below, I can think of two ways to access the individual li elements of an unordered / ordered list generated by the ListBox control.
Create a custom Control that inherits from
the ListBox control and renders out an
id attribute for each li element.
Use the getElementsByTagName method
in JavaScript. MSDN even has an
example that uses the
getElementsByTagName method to get
the children of an unordered list and
displays an alert indicating the
number of children and the value of
the first child element. If the MSDN documentation isn't your thing, you can check out the MDC documentation as well.
You could either use the ClientId property as stated by paper1337
var element = document.getElementById('<%= MyDropDownList.ClientID %>');
or you could implement a AJAX Behavior using AjaxControlToolkit.
Code:
[assembly: WebResource("MyJS.js", "text/javascript")]
[ClientScriptResource("MyBehavior", "MyJS.js")]
public sealed class MyExtender : BehaviorBase {
// can be empty
}
Markup:
<asp:DropDownList runat="server" ID="DDL" />
<my:MyExtender runat="server" TargetControl="DDL" />
MyJS.js (See AjaxControlToolkit samples for details):
...
var element = this.get_element();
...
If you are on asp.net 4.0+, you can use the ClientIDMode="Static" to force asp.net to use the id you have specified. There's a nice explanation on ScottGu's blog, and the MSDN Docs for ClientIDMode are available.
You may also want to try ClientIdMode="Predictable", if you have a lot of generated elements.

Access hiddenfield using Jquery

I have a page that's derived from a master page. On this page, I have a hiddenfield ("hfUser"). How can I access this "hfUser" control and get/set its value using JQuery?
I've tried variants of this:
$(document).ready(function() {
var test = $("#hfUser").val();
alert(test);
});
but test = undefined. I'm guessing I've got the selector wrong, but I don't know how to get an asp hiddenfield. Any ideas?
Thanks
If you are using Asp.net controls, the server will mangle the control ids. It adds a bunch of extraneous control tree hierarchy information into the id. You need to reference what that acutal id is that's getting rendered, which is availble with the ClientID property on the control (hfUser.ClientID) or access your control in a different, more roundabout way, like find the controls parent, then search through its children to find your control.
If you don't have to use the asp.net HiddenField control, try just using a regular old html input.
ASP does like to mangle ID's. The further down the rabbit hole (or nesting controls) you go, the more ASP adds to your control ID. Throw in Master Pages, and it's yet another level or two.
Another way to access server-side controls (with the runat property set), is to use the square brackets in your jQuery selector.
Like this:
$("[id$='hidImgSource']").val()
That selects any elements whose ID has 'hidImgSource' as ending part of the name. So it will find mangled ID's.
Here is a link to the jQuery Selectors page that explains some more options.
If the hidden field is an ASP.NET control, check out this blog post to help you with jQuery selectors for ASP.NET controls
http://www.foliotek.com/devblog/extending-jquery-to-select-asp-controls/
Do it like this:
$(document).ready(function()
{
var test = $("**#<%= hfUser.ClientID %>**").val();
alert(test);
});

Selecting by ID attribute using JQuery in 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;
}

Resources