Is it bad to add a css class that doesn't exist? - asp.net

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.

Related

How to set control properties in css?

Is there a way to set this kind of properties in css?
So I can use the same calendar and be more organized with my code
<asp:Calendar ID="Calendar1" runat="server" Height="189px" CssClass="Calendar"
ondayrender="CalendarRender" TitleStyle-BackColor="#00718F" TitleStyle-ForeColor="White" ShowGridLines="true" TitleStyle-BorderStyle="Solid" TitleStyle-BorderWidth="1px" TitleStyle-BorderColor="Black" SelectedDayStyle-ForeColor="#281dc9" SelectedDayStyle-Font-Bold="true" DayHeaderStyle-BorderColor="Black" DayHeaderStyle-BorderWidth="1px" DayHeaderStyle-BorderStyle="Solid"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
Assuming you're talking about properties such as:
TitleStyle-BackColor="#00718F" TitleStyle-ForeColor="White"
... etc..
Your best bet would be to render the calendar to a page, check its source and see what style it adds. You can then extract this out for use in CSS.
UPDATE
This page has some of the selector names for you, along with what they control ASP.Net Calendar Control Custom Theme Format using CSS
If you want to be more organized, and don't want your project to become like 'spaghetti' in future, use CSS file for css properties. Do not embed this properties in headers, unless this is the only way to solve current issue. This is bad for you, and for all who will work with your project.
I've met lot of legacy projects, wasting too much time to find why some dom element's behaviours differs from what I need.
Just specify CssStyle property in your aspx markup, and it will be mapped to real css class.
And add description for this class in css file.

How can I add properties/attributes to an HTML markup container tag in ASP.Net

I've seen all of the usual pages with information about how to create a sub-tag that allows content within a user control (using ITemplate and INamingContainer) but I've yet to see anyone able to add properties that become attributes to said tags, for example:
<asp:MyControl runat="server" ID="myControlTest" SomeAttribute="SomeValue">
<Content ContentAttribute="Something">
Blah
</Content>
</asp:MyControl>
If you see the ContentAttribute on the Content tag, that is what I'd like to be able to achieve, but if I set it all up using ITemplate and INamingContainer etc, I can add a property that does in fact appear in Intellisense for that tag but when I run the code, it says Content does not have property/attribute named ContentAttribute (it also gives the same as a warning in VS IDE but still allows me to compile it).
I have tried everything to make this work and so far the only way seems to be if I make the Content property on MyControl a class that inherits from System.Web.UI.Control and implements ITemplate. That works but unfortunately I have to specify the runat attribute on the Content tag (because it sees it as a control rather than a sub-tag) and I'd rather not do that if possible.
Hope I have explained this well enough, if I haven't please let me know and I'll do my best to elaborate further.
Thanks in advance.
I think what you're proposing is something like a MIME email where there are a variable number of sections, each with an identifier for the client to choose the best version of the email it can handle. I assume you're wanting to select the appropriate template at runtime, based on that attribute.
The standard .NET controls don't implement that way, so far as I can tell. Think of the Repeater which has:
<asp:Repeater id="myRepeater" runat="server">
<HeaderTemplate>...</HeaderTemplate>
<ItemTemplate>...</ItemTemplate>
<FooterTemplate>...</FooterTemplate>
</asp:Repeater>
Each of the subitems (templates) has a different name, not the same name with a separate attribute.
Is there any way for you to define, ahead of time, what all of the possible sections might be, the way the repeater does?
<asp:MyControl runat="server" ID="myCtlTest">
<SomethingTemplate>Blah</SomethingTemplate>
<OtherTemplate>Blah</OtherTemplate>
</asp:MyControl>
I'm guessing not but wanted to throw it out there in case.
Alternately, could the ContentAttribute move to MyControl? The SETter would then load/build the template for you depending on the value.
<asp:MyControl runat="server" ID="myCtlTest" ContentAttribute="Something">
<Template></Template>
</asp:MyControl>
...or it could be loaded with a method instead of using the property SETter.
If you will always need multiple templates, perhaps a combination of those two concepts would help.
<asp:MyControl runat="server" ID="myControlTest"
SomethingTemplate="Something"
OtherTemplate="Other">
<SomethingTemplate></SomethingTemplate>
<OtherTemplate></OtherTemplate>
</asp:MyControl>

ID naming convention in ASP.NET?

Coming from the world of HTML, XML and PHP its a new way of thinking when making web applications using ASP.NET. I'd like to use the following code in my MasterPage:
<div id="leftnav">
<asp:ContentPlaceHolder ID="leftnav" runat="server">
</asp:ContentPlaceHolder>
</div>
But since leftnav in this example is used twice, Visual Studio make a small but noticable protest. How should I think in this situation, and which is the most appropriate use of naming ID's in ASP.NET.
I don't like the default naming since id="ContentPlaceHolder1" says nothing of the content.
Thank you for listening!
I would call the div "nav" and the placeholder "navPlaceholder". This is because the word "left" implies position, which should be handled soley by your css, not your html. What if the designers decided they wanted to put the navigation on the right? You could do this in your css, but you would end up with something confusing like div #lefnav { float:right; } a trivial example, I know but something to keep in mind.
How about "leftNavPlaceHolder"?
Just as along as your consistent with your naming convention :)
No, the default IDs are terrible. I can't imagine they're meant to be used, it's just that Visual Studio isn't intelligent enough to suggest anything better, and they're not suggesting something semi-intelligent, because they don't want to try to come off as something they're not. Reasonable =)
So make a habit of always changing the default IDs. What you change them to is completely up to you; "leftNavContent"? Pretty much the only thing that's coverned by convention is capitalization, when it comes to IDs.
The only thing that should really change from pure HTML is that you can't use IDs like "left-navigation", i.e. containing hyphens, for server controls.
I would suggest, don't give id to div unless you really need, because it will impact on performance.
Subjective. The obvious answer to this type of question is: Pick something that you like; standardise it, and always follow it.
Personally, I name my things in the following fashion:
<asp:Literal runat="server" ID="ltlDescriptionOfContent" />
or
<asp:PlaceHolder runat="server" ID="plhSendMessage">
</asp:PlaceHolder>
For an area that contains, yes, information about sending a message. But you don't have to do this. Do whatever you want. Just make it consistent. And ideally, convey a little information about what is within.
I prefix all ASP.Net controls with ux to mean user control.
Then you can hook up your String emailAddress = "test#abc.com"; to your uxEmailAddress.Text = emailAddress

VS2010 and CSS: What is the best strategy to individually position form controls

OK, I have a ton of controls on my page that I need to individually place. I need to set a margin here, a padding there, etc. None of these particular styles that I want to apply will be applied to more than control. What is the bets practice for determining at which level the style is placed, etc?
OK, my choices are
1) External CSS file
1A) Using ClientIdMode = Auto (the default)
I could assign a unique CssClass value to the ASP.NET control and, in the external CSS file, create a class selector that would only be applied to that one control.
1B) User Client ID = Predicatable
In the external CSS file, I could determine what the ID will be for the controls of interest and create an ID selector (#ControlID{Style} ). However, I fear maintenance issues due to including/removing parent containers that would cause the ID to change.
1C) User Client ID = Static.
I could choose static IDs for the controls such that I minimize the likelihood of a clash with auto generated IDs (perhaps by prefixing the ID with "StaticID_" and use an external stylesheet with ID selectors.
2) I could place the style right on the control. The only disadvantage here, as I see it, is that style info is brought down each time instead of being cached , which is what I'd get using an external CSS. If a style isn't resused, I personally don't see much benefit to placing it in an external file, though please explain why if you disagree. Is there moire of a reason that "It's nice to have all the CSS in one place?"
Definitely use an external CSS file.
Options 1 A-C are really a personal preference. I would go with ClientIDMode="Static" as it gives you the most control over the Ids and it will simplify accessing the elements with Javascript (if needed). I've always hated the ugly generated Ids in the earlier versions of ASP.NET. Using a unique CSS class for each element kinda defeats the purpose of a class, which is intended for use on multiple elements.
Just to confirm your thoughts of option 2, this is not the best approach. Putting your styles in an external CSS file will result in the file being downloaded once and cached, rather than having inline styles bloat your HTML that is sent to the client each time.

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

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".

Resources