views:

340

answers:

3

I have a partial view (UserControl) that implements a simple pager in my Asp.Net MVC project. This pager needs access to a .js file that needs to be included exactly once, regardless of how many instances of the pager control are present on the parent page.

I've tried to use Page.ClientScript.RegisterClientScriptInclude, but it had no effect (I assume because the code nugget was evaluated too late to impact the head control). Is there any simple alternative?

+1  A: 

Page.ClientScript.RegisterClientScriptInclude is used with the traditional ASP.net.

Since you using asp.net-mvc, all you need is to add the script directive of the js file to the page that uses this user control.

Since it's a good practice to have only one minified css file to all the site, you probably will want to include this file in the main css minified file.

Mendy
Thanks, but this control is intended to be used on multiple pages, and will probably have more than one include once it's finished. I'd rather not have to remember which includes I need for every control I create if at all possible. Although, I suppose I could add them to a master page, if there's no other alternative...
AaronSieb
Since you uses in part in the site, you can use it to all the site, and cache it on the client machine.
Mendy
+2  A: 

Add it to the master page.

Then you can guarantee that it'll only be included once, and you won't forget it.With modern caching, there is really no performance loss on including it on every page.

Alastair Pitts
Not sure I like this approach as then it's always there even is the control isn't loaded. Mind you, i don't actually have a better solution.
griegs
I wouldn't have thought that was really such an issue, but I'm quite happy to be corrected.
Alastair Pitts
It sounds like this is the route to go for any shared dependencies. I'm still not sure if I want all the control-specific JS in the master, though.
AaronSieb
+1  A: 

Set a flag in HttpContext.Current.Items when you send the script in your partial - it's a dictionary that lingers for the whole request. E.g.:

if (!HttpContext.Current.Items.Contains("SentTheScript"))
{
    HttpContext.Current.Items["SentTheScript"] = true;
    Response.Write(Html.ScriptTag("Script"));
}

This way it'll be rendered at most once.

kevingessner
This should work, but it doesn't allow much control over where the script tags end up. It's not possible to group them in the head, or grouped at the bottom of the body, for example.
AaronSieb
This answers the question as written, so it gets the accept.
AaronSieb