Javascript – How to emulate ScriptManager.RegisterStartupScript() in ASP.NET MVC project

asp.netasp.net-mvcjavascriptscriptmanager

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.

Best Solution

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.