views:

2138

answers:

2

I am using ASP.NET MVC project and jQuery to handle async requests. Sometimes for an async request I need an initialization JavaScript snippet to be returned and executed together with an HTML snippet (I want this JavaScript to be rendered on server).

For now I am using my own ScriptsHelper class with a RegisterStartupScript() method (adds data to HttpContext.Current.Items). Then in global.asax HttpApplication.EndRequest() for async requests I append all registered scripts to the output (enclosed in tags). jQuery.fn.load() successfully executes them when the received HTML is appended to the DOM - this is exactly what I need. Do you think it is "correct" (good) solution, or maybe you can suggest something better? Thanks.

+1  A: 

I encountered a similar situation in a project before I started using jquery and wound up resorting to using eval(). I was returning a javascript text snippet as part of the value of a non-visible DOM element along with the rest of the HTML I was inserting into the DOM.

I had a lot of trouble debugging this type of dynamically generated javascript in IE6 so this solution worked out decently for me because I could inspect the value of the DOM element that was getting eval'd. However, I've always been leery of using eval.

It sounds like your solution has a reasonable architecture for the server-side rendering as opposed to my spaghetti-code and this technique looks like it fits right in with the spirit of jQuery.fn.load so I wouldn't worry too much.

nvuono
A: 

Yeah I think that jQuery is calling eval() internally for you - are you using append? I think that this technique works pretty good most of the time. If the data returned from the server is in a list that is repeated you may want to look at using the live function added to jQuery 1.3 It allows you to attach an event to all current and future elements matching your selector. Checkout these articles:

Also as something else to consider is a tool to help manage scripts and css for asp.net mvc. I have been using this and I love it as it combines files as well as compresses them. You can configure it all from you web config too.

Jake Scott