简体   繁体   中英

Registering javascript in aspx calling web.config

I'm trying to make my app more flexible. I'm using a third party component (rich text editor). On the page the component is used, I need to register some javascript. At the moment, this is done so :

<script type="text/javascript" src="../../Resources/Xinha/my_config.js"></script>

I tried some options, like this one but none worked.

<script type="text/javascript" src="<%=ConfigurationSettings.AppSettings["Xinha.PathToPackage"]%>/XinhaCore.js"></script>

Are there any suggestions on what I am missing or isn't this possible? Thanks in advance.

You should be using a site root relative path. From MSDN:

A site-root relative path, which is resolved against the site root. Site-root relative paths are useful if you keep resources that are used throughout the site, such as images or client script files, in a folder that is located under the Web site root.

The line to include it would look like:

<script type="text/javascript" src="/Resources/Xinha/my_config.js"></script>

What you're doing is definitely possible but it can really create some havoc w/ ASP.NET's ajax implementation - ASP.NET Ajax doesn't like "<%=%>" in the header...

You can try either of these approaches from the code behind for something a little safer:

    ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "scriptFromConfig", ConfigurationManager.AppSettings["myScriptUrl"]);

OR

    Page.ClientScript.RegisterClientScriptInclude("scriptFromConfig", ConfigurationManager.AppSettings["myScriptUrl"]);

UPDATE:

Per the recommendation that you not use relative pathing, I fully agree. If you want to have a path that works throughout your site but is referenced from the web.config, make it a virtual path:

<add key="myScript" value="~/scripts/someScript.js"/>

Then in your code:

string scriptPath = VirtualPathUtility.ToAbsolute(ConfigurationManager.AppSettings["myScript"]);

Then use scriptPath in the Page.ClientScript.RegisterClientScriptInclude or ScriptManager.RegisterClientScriptInclude call.

USe the following code and it will do the work:

protected void Page_Load(object sender, EventArgs e)
        {
            Literal l = new Literal();
            l.Text = "<script type='text/javascript' src='../../Resources/Xinha/my_config.js'></script>";
            this.Page.Header.Controls.Add(l);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM