How to use jQuery scripts with MasterPage/Content page scenario? - asp.net

I have created a great stand-alone web form in asp.net utilizing many jQuery features and CSS. It works fine. When I re-create it as a web content form as part of a MasterPage, my jQuery and javascript is completely ignored.
I am referencing the pertinent jQuery and CSS in my of the MasterPage. I have a content placeholder at the bottom of the masterpage called "ScriptContent". In my content page, this is where I plug in the various jQuery methods and javascript.
When I view the page source everything is there. However, it's all being ignored so to speak. What am I doing wrong?

Probably the issue is that when your page is loaded as a content page within a masterpage, the ids of all of the elements are altered to reflect what content page they are in. Thus the ids you are using in jquery won't work.
Options I can think of include:
setting the ids used by jquery programatically from asp.net code (using the clientId of the element)
having your jquery selectors reference some other attribute of your element, such as class (which is unfortunately a bit slower)

I would match the source output of the working version against the output of the non-working version.
Obviously, there's something being rendered out from ASP.NET differently. Getting the difference would tell you what.
Since I have no details, I can only guess...but it sounds like you may have left out some $(document).ready() type functionality to kick off your script somewhere.

Related

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.

Cleaning up .NET HTML generation

I am looking to clean up some of the HTML generated by a .NET 2.0 TreeView controller. Switching to another version/model is not an available option.
My first crack yielded an extended TreeView, with an overridden Render that Regex'd out the text I didn't need and output to the page.
The problem was when I tried to collapse/expanded nodes of the tree, my postback event wasn't fired. My assumption was that I didn't need to do any more overriding as the parent TreeView controller would handle the postback events.
What am I missing?
Use the ASP.NET CSS Control Adapters:
http://www.asp.net/CSSAdapters/TreeView.aspx
Without adapters both use HTML <table> tags. Control adapters can be used so that nested <ul> tags are rendered instead. A combination of CSS and JavaScript can then be used to show and hide portions of the hierarchy of the tree or menu.
When the CSS and JavaScript are removed the adapted HTML degrades into simple nested unordered lists that are easily interpreted by screen readers, etc. You can see this for yourself by setting the theme to None in the Theme Chooser on the left.
You regex'd out something that the control needs to handle postbacks. It may be the highly-convoluted id's or the runat attribute... whatever it is, if you're stuck with web controls, you're stuck with bad html.
Your only true (and non-destructive) way to do what you want is not by extending current controls, but by using Control Adapters. There are already control adapters that use css for positioning. Here's ScottGu's post on these CSS adapters.

Registering Javascript in a cached control

I have a user control that is cached and as part of this control, javascript for loading a swfobject is written to the page. I've tried using ClientScript.RegisterStartupScript to write the javascript to the page, however, when rendered from the cache, the javascript is no longer included. This means the swfobject is not loaded.
Currently I'm writing the script into part of the control's div.InnerHTML, which works, but is there a better way?
No, as far as I know there is no better way.
You can use a Literal or a PlaceHolder instead of a div to put the code in, so that you don't have the extra div, but other than that it can't really be improved. If you want to cache the control, all that it does has to be included in what it renders to the page. When the controls is rendered from the cache the code behind is not executed, so it can't have any side effects outside of the control itself.

Best approach for styling navigation using unordered lists in ASP.NET

In ASP.NET (not MVC), what is the best approach to programmatically setting styles on an unordered list used for navigation so the appropriate menu item is styled as the active item if that page is being viewed?
This would most likely be used in conjunction with a MasterPage.
The answer to your question depends a lot on how you have your list implemented {User control or not, etc}. How I would do it, is implement the list to be generated by a user control.
I'd have the UserControl tag each element with something like:
<{...} class="GeneratedMenuItem"> {...}
And I'd have the appropriate styles in the Style Sheet; of course if it was in a user control then you might be able to use Themes (but that depends on which version of ASP.net you are using.
Good question, I have played around with various methods of doing this since the bad old days of asp, and am yet to find the perfect hammer.
Generally I have used the Request.Url.AbsoluteUri (or similar) as an argument to whatever the rendering function was, and most often set a css class of "current" or similar on the appropriate node, as well as rendering child nodes as needed.
I have most often used an xml/xsl combination, which can usually be worked against most cms platforms, although I have never been that happy with the overhead of firing up an xsl transform just to output a nav list, but if you know xsl, is a very nice tool for generating html, and you can always cache the output - for little static html sites which come up occasionally, I often use this approach in a build process to render static menu markup.
Have also used the aspnet sitemap functionality a few times, which is pretty good if you use the css friendly adapters with it - the default rendering makes very ugly markup.
I found this article earlier this weeek: http://blog.devarchive.net/2008/01/auto-generate-strong-typed-navigation.html which uses t4 templates to make a strongly typed navigation class, and I will definately be investigating that further.
The way I took this approach was to create ASP.NET Hyperlink Controls for each of my navigation items in my master page.
Within the master page, I then created a public method that would assign the appropriate "selected" CSS style to the control I specify:
Public Sub SetNavigationPage(ByVal MenuName As String)
DirectCast(Me.FindControl(MenuName), HyperLink).CssClass = "MenuCurrent"
End Sub
Then in my content pages, I simply had to reference the master page accordingly.
Dim myMaster As EAF = DirectCast(Me.Master, EAF)
myMaster.SetNavigationPage("hypSearchRequest")
This gave me the flexibility to add/remove navigation items on various pages and also be able to assign multiple pages to the administrator navigation option when necessary.
It is also interesting to note that referencing the hyperlink control and setting the Visibility attribute (for hiding administrative pages) didn't work. This is due to the order in which the master and the content pages load. Instead, I created another CSS class that simply set the visibility property and used the same approach as above.

Resources