Best way to register file dynamically in code with forced provider

Developer
Aug 29, 2011 at 10:09 PM

It seems like it's dead simple to register a client resource file and specify the provider when using the control from within an ascx file, however when you want to register the file dynamically in code - it's a bit more complicated. I'm writing here in case I'm missing something obvious, but what's the best way to register a file dynamically in code and also force the provider? For example, I have one resource (plugin.js) and its file path (~/js/plugin.js) and I'd like to render on the page using the PageHeaderProvider.

Developer
Aug 31, 2011 at 7:39 PM

What if i rephrase the question to "Is there a way to...?" - because I can't figure it out. :)

Thanks,

Ian

Coordinator
Sep 2, 2011 at 12:02 AM

You sure can and it's dead simple to register dependencies in code too.

I'd suggest if you ever get stumped like that you just download the source code and have a look at the demo/test web project in there as it has samples for pretty much everything that you can do with CDF.

In WebForms you can use this syntax:

ClientDependencyLoader.GetInstance(http).RegisterDependency("Content.css", "Styles", ClientDependencyType.Css);

In MVC there's an extension method called 'GetLoader' on the ViewContext, ControllerContext and HttpContextBase, so you can use the following syntax (for example if you wanted to dynamically register a dependency from an HtmlHelper):

html.ViewContext.GetLoader().RegisterDependency(priority, resourceUrl, ClientDependencyType.Javascript);

Hope that helps!

Developer
Sep 2, 2011 at 2:43 PM
Edited Sep 2, 2011 at 7:20 PM

Thanks very much for the reply! I guess what I'm really asking though is - why doesn't RegisterDependency have an overload that takes "ForceProvider" so that it jives with the way you can use JsInclude/CssInclude? I'm trying to load a CSS file, in code, using the PageHeaderProvider - and the only way I can figure out how to do it so far is to dynamically create a CssInclude and add it to a placeholder on the page. Which seems a little....strange :)

Thanks again!

Ian

Coordinator
Sep 4, 2011 at 11:34 PM

There is an overload that allows you to do that, however its the base of all overloaded methods: RegisterClientDependencies

you could call it like this for example:

IClientDependencyFile file = new BasicFile(type) { Group = 1, Priority = 2, FilePath = "blah.css", PathNameAlias = "Styles", ForceProvider = "MyProvider" };
RegisterClientDependencies(new List<IClientDependencyFile> { file }, new List<IClientDependencyPath>()); //send an empty paths collection

Developer
Sep 6, 2011 at 1:50 PM

Okay, wasn't as obvious as I thought, still should have seen that though! Thanks again for the help and I appreciate all the work on the project - pretty awesome stuff!

Take care,

Ian

Coordinator
Sep 7, 2011 at 10:43 AM

no problemo, yeah, that overload def isn't obvious :) You could make an extension method though!