【问题标题】:Identifier expected error javascript in aspx page while reading key value from web.config从 web.config 读取键值时,aspx 页面中的标识符预期错误 javascript
【发布时间】:2017-03-14 13:17:10
【问题描述】:

我正在尝试在我的 .aspx 页面中使用 javascript 从 web.config 读取键值。 此页面包含在母版页中,脚本块添加到我的 aspx 页面的 ContentPlaceHolder 标记中,如下所示;这个问题之前在这里问过how to read values from web.config in javascript in aspx page,但没有明确的解决方案。有人建议返回服务器端,但我试图避免返回服务器以加速用户在页面上的工作......所以下面是我的代码:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <script type="text/javascript">

    function CheckCountry() {
        var country = '<%= System.Configuration.ConfigurationManager.AppSettings["LoginCountry"].ToString() %>';
        alert(country);
    }

    window.onload = CheckCountry; 

    </script>
       ....
</asp:Content>

但每当我尝试运行我的项目时,我都会在 Visual Studio 2010 的“列表错误”框中收到此错误。 我也试过这个'&lt;%=ConfigurationManager.AppSettings["LoginCountry"].ToString() %&gt;' 但没有用,同样的错误被抛出...... 可能是什么问题呢?如何解决这个问题并从我的 aspx 页面中的 web.config 获取国家/地区的值?

【问题讨论】:

  • 嗯,当我尝试它时它工作了......你的web.config&lt;appSettings&gt;节点是什么样的?
  • @VDWWD 就是这样
  • 看起来正确。如果您忽略错误会发生什么。或者从 javascript 中删除 '。有时编辑器不理解结合内联代码的 javascript。
  • @VDWWD 如果我忽略它,打开此页面时会抛出它;如果我删除 ' 怎么写?
  • 可能是因为 &lt;location allowOverride="true" inheritInChildApplications="true"&gt; 标签内吗?喜欢这里:&lt;location allowOverride="true" inheritInChildApplications="true"&gt;&lt;appSettings&gt; &lt;add key="LoginCountry" value="LL"/&gt; &lt;/appSettings&gt;&lt;/location&gt;

标签: javascript asp.net web-config key-value


【解决方案1】:

Visual Studo 2010 编辑器似乎对' 和内联代码&lt;%= ... %&gt; 的组合感到困惑。因为在 Studio 2015 中,以下行确实有效:

var country = '<%= System.Configuration.ConfigurationManager.AppSettings["LoginCountry"].ToString() %>';

您可以尝试在代码中用javascript创建整行,也许编辑器不会混淆。

<%= "var country2 = '" + System.Configuration.ConfigurationManager.AppSettings["LoginCountry"].ToString() + "';" %>

或者在后面的代码中:

public string javaScript;
protected void Page_Load(object sender, EventArgs e)
{
    javaScript = "var country = '" + ConfigurationManager.AppSettings["LoginCountry"].ToString() + "';";
}

然后在aspx页面上

function CheckCountry() {
    <%= javaScript %>
    .... etc
}

【讨论】:

  • 代码在哪里?你是说后面的代码吗?你能给我一个例子吗,因为我把它粘贴到我的javascript函数而不是var country = '&lt;%= System.Configuration.ConfigurationManager.AppSettings["LoginCountry"].ToString() %&gt;'; ,但它抛出了一个错误:运算符'+'没有为'String'和'System.Collections.Specialized.NameValueCollection'类型定义.
  • 如果它在代码后面,我的 aspx 页面是否可以在 Window.onload 事件中看到它?
  • 第一个例子都内联在 aspx 页面上(由&lt;%= %&gt;重新调整
  • 感谢您的回复,最终将 javaScriptVal 声明为公共字符串(如您所建议的那样),然后以这种方式直接用配置值填充它:javaScriptval = System.Configuration.ConfigurationManager.AppSettings("LoginCountry").ToString,而不是我在我的javascript 函数:var t = '&lt;%= javaScriptval %&gt;'; alert(t); 并提醒 LL。我在按钮单击时尝试了此解决方案,它工作正常,并且在提醒时它不会返回服务器端以获取公共值。
  • 我发现了我的错误:[] 是用于 c# 而 () 是用于 .NET,现在它的工作就像一个亮点
猜你喜欢
  • 2012-10-13
  • 2019-05-21
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多