How can I use a traditional HTML id attribute with an ASP.net runat='server' tag? - asp.net

I am refactoring some CSS on a website. I have been working on, and noticed the absence of traditional HTML IDs in the code.
There is heavy use of CssClass='…', or sometimes just class='…', but I can't seem to find a way to say id='…' and not have it swapped out by the server.
Here is an example:
<span id='position_title' runat='server'>Manager</span>
When the response comes back from the server, I get:
<span id='$aspnet$crap$here$position_title'>Manager</span>
Any help here?

Use jQuery to select the element:
$("span[id$='position_title']")....
jQuery's flexible selectors, especially its 'begins with'/'ends with selectors' (the 'end with' selector is shown above, provide a great way around ASP.NET's dom id munge.
rp

The 'crap' placed in front of the id is related to the container(s) of the control and there is no way (as far as I know) to prevent this behavior, other than not putting it in any container.
If you need to refer to the id in script, you can use the ClientID of the control, like so:
<script type="text/javascript">
var theSpan = document.getElementById('<%= position_title.ClientID %>');
</script>

Most of the fixes suggested her are overkill for a very simple problem. Just have separate divs and spans that you target with CSS. Don't target the ASP.NET controls directly if you want to use IDs.
<span id="FooContainer">
<span runat="server" id="Foo" >
......
<span>
</span>

You can embed your CSS within the page, sprinkled with some server tags to overcome the problem. At runtime the code blocks will be replaced with the ASP.NET generated IDs.
For example:
[style type="text/css"]
#<%= AspNetId.ClientID %> {
... styles go here...
}
[/style]
[script type="text/javascript"]
document.getElementById("<%= AspNetId.ClientID %>");
[/script]
You could go a bit further and have some code files that generate CSS too, if you wanted to have your CSS contained within a separate file.
Also, I may be jumping the gun a bit here, but you could use the ASP.NET MVC stuff (not yet officially released as of this writing) which gets away from the Web Forms and gives you total control over the markup generated.

Ok, I guess the jury is out on this one.
#leddt, I already knew that the 'crap' was the containers surrounding it, but I thought maybe Microsoft would have left a backdoor to leave the ID alone. Regenerating CSS files on every use by including ClientIDs would be a horrible idea.
I'm either left with using classes everywhere, or some garbled looking IDs hardcoded in the css.

#Matt Dawdy: There are some great uses for IDs in CSS, primarily when you want to style an element that you know only appears once in either the website or a page, such as a logout button or masthead.

The best thing to do here is give it a unique class name.

You're likely going to have to remove the runat="server" from the span and then place a within the span so you can stylize the span and still have the dynamic internal content.
Not an elegant or easy solution (and it requires a recompile), but it works.

.Net will always replace your id values with some mangled (every so slightly predictable, but still don't count on it) value. Do you really NEED to have that id runat=server? If you don't put in runat=server, then it won't mangle it...
ADDED:
Like leddt said, you can reference the span (or any runat=server with an id) by using ClientID, but I don't think that works in CSS.
But I think that you have a larger problem if your CSS is using ID based selectors. You can't re-use an ID. You can't have multiple items on the same page with the same ID. .Net will complain about that.
So, with that in mind, is your job of refactoring the CSS getting to be a bit larger in scope?

I don't know of a way to stop .NET from mangling the ID, but I can think of a couple ways to work around it:
1 - Nest spans, one with runat="server", one without:
<style type="text/css">
#position_title { // Whatever
}
<span id="position_titleserver" runat="server"><span id="position_title">Manager</span></span>
2 - As Joel Coehoorn suggested, use a unique class name instead. Already using the class for something? Doesn't matter, you can use more than 1! This...
<style type="text/css">
.position_title { font-weight: bold; }
.foo { color: red; }
.bar { font-style: italic; }
</style>
<span id="thiswillbemangled" class="foo bar position_title" runat="server">Manager</span>
...will display this:
Manager
3 - Write a Javascript function to fix the IDs after the page loads
function fixIds()
{
var tagList = document.getElementsByTagName("*");
for(var i=0;i<tagList.length;i++)
{
if(tagList[i].id)
{
if(tagList[i].id.indexOf('$') > -1)
{
var tempArray = tagList[i].id.split("$");
tagList[i].id = tempArray[tempArray.length - 1];
}
}
}
}

If you're fearing classitus, try using an id on a parent or child selector that contains the element that you wish to style. This parent element should NOT have the runat server applied. Simply put, it's a good idea to plan your structural containers to not run code behind (ie. no runat), that way you can access major portions of your application/site using non-altered IDs. If it's too late to do so, add a wrapper div/span or use the class solution as mentioned.

Is there a particular reason that you want the controls to be runat="server"?
If so, I second the use of < asp : Literal > . . .
It should do the job for you as you will still be able to edit the data in code behind.

I usually make my own control that extends WebControl or HtmlGenericControl, and I override ClientID - returning the ID property instead of the generated ClientID. This will cause any transformation that .NET does to the ClientID because of naming containers to be reverted back to the original id that you specified in tag markup. This is great if you are using client side libraries like jQuery and need predictable unique ids, but tough if you rely on viewstate for anything server-side.

If you are accessing the span or whatever tag is giving you problems from the C# or VB code behind, then the runat="server" has to remain and you should use instead <span class="some_class" id="someID">. If you are not accessing the tag in the code behind, then remove the runat="server".

Related

Is it bad to add a css class that doesn't exist?

I want to add a bunch of classes to some text fields so i can get their values with jquery. This seems like standard practice when using jQuery and this post suggests it as the answer but how does this affect page loading? Won't it be trying to find all these classes? I have been told in the past to try minimise the amount of classes used on controls.
I have about 12 controls i'll want to add unique classes to to get their value. I am using asp.net so I can't use the id. I also can't use the ClientID as the controls are in a table (but only 1 set of controls will show at any one time).
e.g.
<asp:TextBox ID="txtValue1" runat="server" CssClass="value1" Text='value1' />
<asp:TextBox ID="txtValue2" runat="server" CssClass="value2" Text='value2' />
<asp:TextBox ID="txtValue3" runat="server" CssClass="value3" Text='value3' />
...
var value1 = $('.value1').val();
var value2 = $('.value2').val();
var value3 = $('.value3').val();
And none of the class names will exist in css.
Thanks
Edit:
I know this works but I was more curious about the affect it had on page loading. There was an answer (seems to be deleted now) that said something like the html parser ignores the classes. The css parser will only look at classes that are defined. So it sounds like it would be completely ignored and have no affect on page load. Is this right?
It is okay to use a CSS class that doesn't exist, but if they are unique you want to use id, not class.
You say you are using ASP.Net so you can't use the ID parameter, but you can. In JQuery you can get the controls using the below
var value1 = $('[ID$=yourID]').val();
For more info on JQuery Selectors check out: JQuery Selectors and Attribute Ends With Selector
The above selector basically finds the id ENDING in "yourID" so ignoring all the masterpages extra text at the start. You just have to make sure these are unique. e.g. don't have ids like "HSBC" and "SBC" as the above selector on "SBC" will find both.
I don't think it's a problem. The only times I've had problems with non-existant classes or ID's is one time I had an onclick reference an ID that didn't exist. This messed things up...Other than that I think classes are pretty harmless. I'd be interested to know though..
Any other thoughts??
Which version of asp.net are you using? In asp.net 4.0, you have the ability to use unmangled ids. It looks like the simplest solution would be to set ClientIDMode="Static" to all of your textboxes and then refer by id. Otherwise, sure, I've created classes that don't exist to refer to things.... all the time.
Edit: (in response to your comment about the effect page load).
I think your question about having extra classes in a div that are not currently used is not a bad question (at least in a theoretical sense), and I honestly don't know the precise answer. I do believe any effect is quite minuscule. If you consider best practices to write html, you generally write and structure the HTML, with it's classes, before you write the CSS. This means at the time you write the CSS, certainly some classes will not be used. Indeed, after styling the basic tags (body, h1, a, etc), you may find you never need to create selectors with those classes for some particular design. And yet for the next design, you might need those classes. I'm pretty sure the technology behind CSS was built with those kinds of scenarios in mind, and I bet millions if not billions of pages on the internet follow that exact scenario, especially if they use something like Modernizr, which adds classes to the html element of the page as a way of providing you classes you can select against considering the possible capabilities of the current browser. You may never need those classes, but they are there if you need them.

css tabs that do not require div changes for the active tab

I'm looking to get ideas on how to not change at all the code used to create css tabs (so that I can place it into an include file to avoid duplicating the code across all files that use it), but my current implementation doesn't allow this because I need to select the active tab using id="selectedTab".
The only implementation I found so far that solves this is the following one:
http://unraveled.com/publications/css_tabs/
It requires assigning a class to each tab and uses the body id to determine the active tab.
Is this the only way or is there any other alternatives?
My current code looks like this (the id=noajax" is used to avoid using ajax to load certain pages):
<div class="productTabsBlock2">
<a id="selectedTab" href="/link1" >OVERVIEW</a>
SCREENSHOTS
<a id="noajax" href="/link3" >SPEED TESTS</a>
<a href="/link4" >AWARDS</a>
</div>
EDIT: asp is available as server side and is already used on these pages.
If you're looking for a non-JS solution, then the body class/id provide the easiest way to do what you want.
If you have access to JS library, you can easily add "selected" class to any of the <a> element and modify its appearance.
Just in case you haven't notice, you can use more than one class definition in an element. For example, <a class="noajax selected" /> is valid and both CSS selectors .noajax and .selected will be applied to the element.
An include file for what? If it's a server side programming language like PHP, you can pass a parameter for the selected tab through various methods.
you could use jQuery to add the `selectedTab' id (or class) like so
$('.productTabsBlock2 a').mouseover(function () {
$(this).addClass('selectedTab');
});

How do I access a DIV from javascript, if ASP.NET mangles its ID?

I have a web page that contains a "div" element. On the page, there is javascript to reference the div: document.getElementById('divId'). This was working fine until another developer redesigned the page to use an ASP master page.
Now, document.getElementById('divId') returns null. It appears that ASP.net prepends some characters to the names of elements within contents forms when you use a master page. How can I know what the id of the div is when the page loads?
Update Allow me to give a specific example to clarify the question: My page had a div with ID divNotice. After changing my page to use a master page, I see when I print the source to the page that renders that the div ID is ctl00_ContentPlaceHolder1_divNotice. My question is, how am I supposed to know what the div ID is going to be when the framework is done with it?
I think that this is what you looking for.
document.getElementById('<%=divNotice.ClientID%>')
to get the ID of your element as appears on the html page use .ClientID
Hope this help.
Dynamically create the javascript using Control.ClientID to determine the calculated ID of div.
document.getElementById('<%= DivControl.ClientID %>')
Or search for the element on the client side using the base ID as a search pattern. See here: A generic way to find ASP.NET ClientIDs with jQuery
I prefer the server side calculation, but if you don't do it often and/or your current design prohibits it, the client side way is a reasonable workaround.
you can check i the element exists by checking if it returns not null
if (document.getElementById('divId') != null) { /* do your stuff*/ }
in other words:
if (document.getElementById('divId')) { /* do your stuff*/ }
now you have edited you orginal question i got it.. i would do something like this:
var arrDivs = document.getElementsByTagName('div'),
strDivName = "divId";
for (i=0;i<=arrDivs.length;i++){
if( arrDivs[i].id.indexOf(strDivName) != -1) {
alert("this is it")
}
}
you can see a demo here:
http://jsfiddle.net/pnHSw/2/
i think you could do it better with a regex.
But this is a pure JS way i don't know ASP.net
edit: i think Aristos solution is much cleaner :P
maybe you can use a descendent selector un css
<div id="wrapperControler">
<controler id="controler"></controler>
</div>
wrapperControler controler{
dosomething;
}

Unobtrusive JavaScript with server side values, best practice?

I'm used to do doing things like this:
<a href="Javascript:void(0);" onclick="GetCommentForGeneralObservation(<%# Eval("ID") %>)">
That would be in a repeater or such like btw. However I an now trying to use unobtrusive JavaScript and hence get rid of any JS in the markup. I was trying to figure out what the best practice is in cases like this? I've used attributes and then got the value using JQuery to pass to the AJAX call but it seems a bit of a hack.
Edit in light of first reply:
I was thinking more of the
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation.
part of unobtrusive JS as I understand it.
This happens to be for an application where I don't have to worry about Javascript being turned off on the client, it's hosted internally at my company. What I was getting at was how would I get the value from Eval("ID") into the JS call if I were to attach the onclick event in a separate .js file via JQuery.
Sorry for not being clearer. I appreciate the need for progressive enhancement in public facing apps.
In HTML 5 you are allowed to define your own attributes prefixed with 'data-'
e.g.
<a
class="comment"
data-rendered-id="<%# Eval("ID") %>"
href="/getCommentForGeneralObservation/<%# Eval("ID") %>" >
And then use that attribute in jQuery in your click event handler.
$(".comment").click(function () {
var id = $(this).attr("data-rendered-id");
return GetCommentForGeneralObservation(id);
});
This will work in most pre-HTML5 browsers too as long as they support jQuery.
Note that in unobtrusive javascript you really should support non-javascript browsers, hence you need an href attribute that works as well.
I'd start with:
<a href="/getCommentForGeneralObservation/<%# Eval("ID") %>" class="getCommentForGeneralObservation">
and then attach an event handler that looked something like this:
function (event) {
var href = this.href;
var id = href.search(/\/(\d+)/);
return GetCommentForGeneralObservation(id);
};
Unobtrusive means you don't depend on Javascript for functionality and therefore your code is extended with Javascript rather than replaced by it.
In your case, you're embedding Javascript directly in the link, and worse off, the link won't work at all without Javascript enabled. Instead you'll want something like this, which is pure HTML without any reference to Javascript:
<a id="commentLink" href="comment.asp">Get Comment</a>
And your Javascript (assuming you're not using a framework) would be something like:
function GetCommentForGeneralObservation(evt) {
// Extra javascript functionality here
}
document.getElementById("commentLink").onclick = GetCommentForGeneralObservation;
With Jquery I believe you could just do:
$("#commentLink").click(GetCommentForGeneralObservation);
I'm going to re-answer this because I understand the question now and the approach I usually use is different from what has been suggested so far.
When there's no way to avoid having dynamic content, I will usually do the following:
<script type="text/javascript">
var myApp = {commentId:<%# Eval("ID") %>};
</script>
<script type="text/javascript" src="myAppScript.js"></script>
Now, in myAppScript.js, you can use myApp["commentId"] wherever you need that ID to be referenced. (I use a dictionary so as to not pollute the global namespace)
The advantage of this approach is that your myAppScript.js is still completely static and so you can serve it very fast. It also has the advantage of keeping the relevant information out of the URL and you can use Javascript objects, which can help a lot with complex and/or hard-to-parse data.
The disadvantage is that it requires inline Javascript, which isn't much of a disadvantage unless you're a web perfectionist.
I also really like DanSingerman's approach, which is more suited if your data is specific to a tag.
You might wish to use JQuery metadata plugin, or the core data function.
http://docs.jquery.com/Core/data
http://plugins.jquery.com/project/metadata
You could use the rel attribute of the anchor tag to store the value you want to associate with the link.
Click Here
Then in your jQuery code you can check the rel attribute to get the value you're looking for.
$(".comment").click(function () {
return GetCommentForGeneralObservation(this.rel);
});
(Pretty sure this is accurate for jQuery, but I'm more of a MooTools guy...)
How about making sure it is fully unobtrusive?
In the head of the HTML document
<script src="path/to/php/or/other/equivalent/server/side/file"></script>
In the path/to/php/or/other/equivalent/server/side/file:
var SiteServerVariablesEtc = {
someProperty: <?php echo "hello" ?>
}
In your normal JS file:
var myVar = SiteServerVariablesEtc.someProperty;

How to prevent a hyperlink from linking

Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?
I know that marking it as disabled works but then it gets displayed differently (greyed out).
To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.
I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.
This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page:
$(document).ready(function() {
$('a.NoLink').removeAttr('href')
});
All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text.
A single line of JQuery can solve your problem.
I'm curious on what it is you which to accomplish with that. Why use a link at all?
Is it just for the formatting? In that case, just use a <span> in HTML and use stylesheets to make the format match the links.
Or you use the link and attach an onClick-Event where you "return false;" which will make the browser not do the navigation - if JS is enabled.
But: Isn't that terribly confusing for your users? Why create something that looks like a link but does nothing?
Can you provide more details? I have this feeling that you are trying to solve a bigger problem which has a way better solution than to cripple a link :-)
A Hyperlink control will render as a "a" "/a" tag no matter what settings you do. You can customize a CSS class to make the link look like a normal label.
Alternatively you can build a custom control that inherits from System.Web.UI.WebControls.HyperLink, and override the Render method
protected override void Render(HtmlTextWriter writer)
{
if (Enabled)
base.Render(writer);
else
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(Text);
writer.RenderEndTag(HtmlTextWriterTag.Span);
}
}
}
Could be a bit overkill, but it will work for your requirements.
Plus I find is usefull to have a base asp:CustomHyperlink asp:CustomButton classes in my project files. Makes it easier to define custom behaviour throughout the project.
If you merely want to modify the appearance of the link so as not to look like a link, you can set the CSS for your "a" tags to not have underlines:
a: link, visited, hover, active {
text-decoration: none;
}
Though I would advise against including "hover" here because there will be no other way to know that it's a link.
Anyway I agree with #pilif here, this looks like a usability disaster waiting to happen.
If you mean to stop the link from activating, the usual way is to link to "javascript:void(0);", i.e.:
foo
This should work:
onclick="return false;"
if not, you could change href to "#" also. Making it appear as a rest of text is css, e.g. displaying arrow instead of hand is:
a.dummy {
cursor:default;
}
Thanks for all the input, it looks like the short answer is 'No you can't (well not nicely anyway)', so I'll have to do it the hard way and add the conditional code.
If you are using databind in asp.net handle the databinding event and just don't set the NavigateUrl if that users is disabled.
Have you tried just not setting the NavigateUrl property? If this isn't set, it may just render as a span.
.fusion-link-wrapper { pointer-events: none; }
Another solution is apply this class on your hyperlink.
.avoid-clicks {
pointer-events: none;
}
CSS solution to make tags with no href (which is what asp:HyperLink will produce if NavigateURL is bound to null/empty string) visually indistinguishable from the surrounding text:
a:not([href]), a:not([href]):hover, a:not([href]):active, a:not([href]):visited {
text-decoration: inherit !important;
color: inherit !important;
cursor: inherit !important;
}
Unfortunately, this won't tell screen readers not to read it out as a link - though without an href, it's not clickable, so I'm hoping it already won't be identified as such. I haven't had the chance to test it though.
(If you also want to do the same to links with href="", as well as those missing an href, you would need to add pointer-events:none as well, since otherwise an empty href will reload the page. This definitely leaves screen readers still treating it as a link, though.)
In the OP's use case, if you still have the href being populated from the database but have a boolean value that indicates whether the link should be a 'real' link or not, you should use that to disable the link, and add a:disabled to the selector list above. Then disabled links will also look like plain text rather than a greyed-out link. (Disabling the link will also provide that information to screen readers, so that's better than just using pointer-events: none and a class.)
A note of caution - if you add these sorts of rules globally rather than for a specific page, remember to watch out for cases where an tag has no (valid) href, but you are providing a click handler - you still need those to look/act like links.

Resources