user2864740
user2864740

Reputation: 61925

Get the ".ascx" path of a User Control

Context:

I have created a custom "Script" control that I use in several of my User Controls (these are all loaded via an ASCX path). This Script control provides several interesting features, but I would now like to be able to move the script out of the ASCX markup into the same directory as the ASCX control and then load this markup dynamically. (I cannot use normal <script> tags because the Script control creates a special binding context such that it can be accessed through a clean API.)

That, currently my Script control is used like (the <script> elements inside are consumed by the Script control and should not be confused with the final HTML markup):

<SmartScript runat="server">
  <script>/* the code here */</script>
</SmartScript>

But I would like it to be usable as:

<SmartScript runat="server">
  <script src="~parent/theCode.js" />
</SmartScript>

However, I want "~parent" to be expanded to the filesystem location of the ASCX control so that I can load the file directly and use that as the contents for the rendered script.

That is, given the ASCX-based user control (which can be obtained through the Parent property), how is it possible to determine the system path which houses the ASCX markup file? (And, what caveats should I be aware of?)

Preferably, this would be the complete path as something like ~/_CONTROLTEMPLATES/prj/ctrl.ascx" still leaves another layer of redirect (what does the ~ mean here?) to work through.

(The application runs with enough trust to read from the filesystem, and I am avoiding embedded resources so I can push Layout changes without needing to push the DLLs and restart the IIS workers.)

Upvotes: 2

Views: 2388

Answers (1)

user2864740
user2864740

Reputation: 61925

Well, this was ridiculously simple. I imagine it will only be meaningful for controls with markup, but it seems to work just fine here.

Control.TemplateSourceDirectory can be used in conjunction with Control.MapPathSecure.

The example from the documentation is:

output.Write("The Actual Path of the virtual directory : " + MapPathSecure(TemplateSourceDirectory));

Upvotes: 5

Related Questions