Brian Webster
Brian Webster

Reputation: 30865

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.

Upvotes: 0

Views: 126

Answers (3)

Jimmy Chandra
Jimmy Chandra

Reputation: 6580

Let's see...

  1. 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 :).

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

Upvotes: 1

Jason Berry
Jason Berry

Reputation: 2469

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.

Upvotes: 3

Colin Mackay
Colin Mackay

Reputation: 19175

You could put the javascript code into separate js file(s). You then reference the js file(s) in your page.

Upvotes: 5

Related Questions