views:

278

answers:

2

Is there any MVC equivalent to Page.ClientScripts.RegisterClientScriptInclude and Page.ClientScripts.RegisterClientScriptBlock?

I am looking to create Partial Views which may very well be referenced multiple times from the same main view.

These views might very well have their own script requirements but it seems wasteful to write includes on every potential main view or master page.

Also I feel that it would be sensibel to have the Partial view call some javascript once to initialise all of it's sibling views.

For example...

$('input[alt=date]').datepicker();

...is something which I should really only have to call once, but only if a partial view has placed such a hmtl control in the view.

So any ideas how I can achieve the old Page.ClientScripts.RegisterClientScriptInclude and Page.ClientScripts.RegisterClientScriptBlock functionality within the ASP.Net MVC Framework

+3  A: 

I've done this with an extension method on the HtmlHelper Html.RegisterJavascript( string ). I create a key, "__javascript__", in the ViewData dictionary. This holds a dictionary of javascript entries keyed off of a digest of the javascript (to prevent duplicates).

The problem is that these registrations happen after the header has been processed, so script tags have to go at the end of the file. Before the body end tag, I have a call to Html.RenderJavascript(); (my method).

I couldn't find a better way, but I have to imagine a more clever solution is possible.

Ryan Emerle
+3  A: 

You can use Spark view engine, that has "once" attribute for this purpose. E.g.

<content name="MasterPageHead">
  <script once="CustomScriptUniqueIdName" ... />
</content>

When used in a view or a partial, script (or this can be any other tag, e.g. div) will only be included once in the master page section called MasterPageHead (which you can place in <head>).

Not sure if this will be helpful for you, but you asked for a MVC solution, not WebForms solution.

queen3