javascript 从javascript读取AppSettings

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12906806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:24:54  来源:igfitidea点击:

Reading AppSettings from javascript

javascriptasp.netc#-4.0

提问by Chad Richardson

I'm trying to create a function that retrieves a web.config app settings value. This works if I put the code alert('<%=ConfigurationManager.AppSettings["facebookAppID"].ToString() %>')in the .ascx file directly. But if I call a common function in a .js file from that .ascx file (so as to have a common global function), it doesn't work...i.e. it doesn't evaluate the value but instead just returns the string "<%=System.ConfigurationManager.AppSettings[\"facebookAppID\"].ToString(); %>"

我正在尝试创建一个检索 web.config 应用程序设置值的函数。如果我将代码alert('<%=ConfigurationManager.AppSettings["facebookAppID"].ToString() %>')直接放在.ascx 文件中,这会起作用。但是,如果我从该 .ascx 文件中调用 .js 文件中的通用函数(以便具有通用的全局函数),则它不起作用......即它不评估值,而是只返回字符串"<%=System.ConfigurationManager.AppSettings[\"facebookAppID\"].ToString(); %>"

Any thoughts as to why this is?

关于为什么会这样的任何想法?

function GetappId() {
    var k = "<%=System.ConfigurationManager.AppSettings["facebookAppID"].ToString(); %>"
    alert(k);
return k
}

采纳答案by Mark Alicz

Common .js files if your including them like this script src="somescript.js" /script are loaded on the clients browser and are never processed on the server.

常见的 .js 文件,如果你像这个脚本 src="somescript.js" /script 那样包含它们,它们会加载到客户端浏览器上,并且永远不会在服务器上进行处理。

Only way to load files/values using javascript would be to perform and ajax call to an aspx page that returns either JSON or text..

使用 javascript 加载文件/值的唯一方法是对返回 JSON 或文本的 aspx 页面执行和 ajax 调用。

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

回答by Tariqulazam

Please note this will only cater for the appSettings section in the web.config

请注意,这仅适用于 web.config 中的 appSettings 部分

  1. I created an .aspxfile called DynamicJs.aspxas below. It will grab the key value pair from the appSettings and construct a JSON string.

    code behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Web.Script.Serialization;
    using System.Collections.Specialized;
    
    public partial class DynamicJs : System.Web.UI.Page
    {
        private string settingsJson = string.Empty;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            NameValueCollection nvc = ConfigurationManager.AppSettings;
            var dict = new Dictionary<string, string>();
            foreach (string key in nvc.Keys)
            {
                dict.Add(key, nvc[key]);
            }
            settingsJson = new JavaScriptSerializer().Serialize(dict);
        }
    
        public string GetSettingsJson() {
            return settingsJson;
        }
    }
    

    HTML(Please note the content type, as it will emit JavaScript)

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicJs.aspx.cs" Inherits="DynamicJs" ContentType="text/javascript" %>
    
    function GetValue(key){
        var data= <%=GetSettingsJson() %>;
        return data[key];
    }
    
  2. Include the DynamicJs.aspx in the consuming page as below:

    <script src="DynamicJs.aspx" type="text/javascript"></script>
    
  3. Use the following to get value from the configuration

    <script>
        alert(GetValue("key2"));
    </script>
    
  1. 我创建了一个.aspx名为DynamicJs.aspx的文件,如下所示。它将从 appSettings 中获取键值对并构造一个 JSON 字符串。

    背后的代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Web.Script.Serialization;
    using System.Collections.Specialized;
    
    public partial class DynamicJs : System.Web.UI.Page
    {
        private string settingsJson = string.Empty;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            NameValueCollection nvc = ConfigurationManager.AppSettings;
            var dict = new Dictionary<string, string>();
            foreach (string key in nvc.Keys)
            {
                dict.Add(key, nvc[key]);
            }
            settingsJson = new JavaScriptSerializer().Serialize(dict);
        }
    
        public string GetSettingsJson() {
            return settingsJson;
        }
    }
    

    HTML(请注意内容类型,因为它会发出 JavaScript)

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicJs.aspx.cs" Inherits="DynamicJs" ContentType="text/javascript" %>
    
    function GetValue(key){
        var data= <%=GetSettingsJson() %>;
        return data[key];
    }
    
  2. 在消费页面中包含 DynamicJs.aspx 如下:

    <script src="DynamicJs.aspx" type="text/javascript"></script>
    
  3. 使用以下命令从配置中获取值

    <script>
        alert(GetValue("key2"));
    </script>
    

It is definitely not the most elegant way of doing this, but I think it will help you achieve what you wanted.

这绝对不是最优雅的方式,但我认为它会帮助你实现你想要的。

回答by th1rdey3

one way to do it is to use a Custom Control page. Add an Web User Control (.ascx)page in your website and put your script code in it

一种方法是使用自定义控件页面。Web User Control (.ascx)在您的网站中添加一个页面并将您的脚本代码放入其中

<script type="text/javascript">
    function GetappId() {
        var k = "<%=System.ConfigurationManager.AppSettings["facebookAppID"].ToString(); %>"
        alert(k);
        return k
    }
</script>

now register your control to the page where you want the GetappIdfunction like this

现在将您的控件注册到您想要这样的GetappId功能的页面

<%@ Register TagPrefix="Scrpt" TagName="GlobalScrpt" Src="~/WebUserControl.ascx" %>

** this tag goes after the <%@ Page %>tag in aspxpage

** 此<%@ Page %>标签位于aspx页面中的标签之后

then in the head section of your aspxpage call the control like this

然后在aspx页面的头部部分调用这样的控件

<head runat="server">
    <title></title>
    <Scrpt:GlobalScrpt ID="Scrpt1" runat="server" />
</head>

** ensure you have runat="server"in you header tag

** 确保您有runat="server"标题标签

now you can call GetappId()and get the desired result anywhere in the aspxpage.

现在您可以GetappId()aspx页面的任何位置调用并获得所需的结果。

update - another solution

更新 - 另一个解决方案

another way is to create an aspx(let's say the page is Default1.aspx) page without separate code behind page and place your code there

另一种方法是创建一个aspx(假设页面是Default1.aspx)页面,而没有单独的代码隐藏在页面后面,并将您的代码放在那里

<%@ Page Language="C#" %>

function GetappId()
{
    var k = "<%=System.ConfigurationManager.AppSettings["facebookAppID"].ToString(); %>";
    alert(k);
}

then in the page where you want to call GetappId add the first aspxpage as a javascript page.

然后在要调用 GetappId 的aspx页面中将第一页添加为 javascript 页面。

<head runat="server">
    <title></title>
    <script type="text/javascript" src="Default1.aspx"></script>
</head>

now call your function anywhere in the page.

现在在页面的任何地方调用你的函数。

回答by andleer

You could inject javascript into your markup using the ClientScriptManagerRegisterClientScriptBlock()or RegisterStartupScript()and include your app settings inline or invoke a method and pass the setting as a parameter.

您可以使用ClientScriptManagerRegisterClientScriptBlock()or将 javascript 注入到您的标记中,RegisterStartupScript()并内联包含您的应用程序设置或调用一个方法并将设置作为参数传递。

Another approach would be to render a hidden field and include your setting there and then reference it in your javascript code.

另一种方法是呈现一个隐藏字段并在那里包含您的设置,然后在您的 javascript 代码中引用它。