This is a migrated thread and some comments may be shown as answers.

Adding inline JavaScript to ScriptRegistrar

3 Answers 167 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Rick
Top achievements
Rank 1
Rick asked on 11 Jun 2010, 07:49 PM
How would you go about adding inline JavaScript using the ScriptRegistrar?

I realize it is desirable to place JavaScript in external files, but there are scenarios where server code needs to dynamically assign a value to a JavaScript variable.

Take for this example.  Say I have a custom component implemented as a partial view.  I want to keep all of my related code together.  How would I ensure my inline JavaScript gets appended to the end of the HTML document and after the <script> elements rendered by the ScriptRegistrar?  (Assume the inline JavaScript has a dependency on an external script rendered by the ScriptRegistar.)

Example Code:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %> 
<%: Html.MyCustomComponent %> 
<script type="text/javascript">  
    var MyDynamicVariable = '<%: Model.MyDynamicVariable %>';  
    DoSomething(MyDynamicVariable);  
</script> 

Added June 15, 2010
One workaround I thought of right after I posted the above was to simply store any server-side generated values in a hidden form field and then let your JavaScript code (called from an external file) have a dependency on the hidden form field.

However I think it would be good to also have the option to inline the JavaScript and have it render at the end of the HTML document with the rest of the script elements.

Added August 30, 2010
It seems we can use the ScriptRegistrarBuilder.OnDocumentReady(string) method to inline any JavaScript we would want executed after the page loads.

Instead of inlining the script block we could just initialize a user-defined, global JavaScript object or variable that was defined in a .js already loaded.

3 Answers, 1 is accepted

Sort by
0
luke
Top achievements
Rank 1
answered on 15 Jun 2010, 03:24 PM
I'm also having trouble with this. Anyone know workaround? 
0
Rick
Top achievements
Rank 1
answered on 15 Jun 2010, 05:19 PM
{Merged with original post above.}
0
James
Top achievements
Rank 1
answered on 17 Aug 2010, 05:16 PM
I agree - this feature is really necessary.  I find myself doing that kind of thing all the time-  some of it could go in the OnDocumentReady block, but it makes more sense to have some things available to the script engine *before* document ready.



Tags
General Discussions
Asked by
Rick
Top achievements
Rank 1
Answers by
luke
Top achievements
Rank 1
Rick
Top achievements
Rank 1
James
Top achievements
Rank 1
Share this question
or