Reputation: 1189
I am trying to read key value from web.config using javascript in my .aspx page. This page is included in a master page, the script block is added in the ContentPlaceHolder tag in my aspx page as below; This question was asked before here how to read values from web.config in javascript in aspx page but there was no clear solution. Someone suggested returning to server side but I am trying to avoid returning to server in order to accelerate user's work on the page ... So below is my code:
<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>
But whenever I try to run my project I get this error in the List Error box in visual Studio 2010.
I have tried also this '<%=ConfigurationManager.AppSettings["LoginCountry"].ToString() %>'
but didn't work, same error was thrown ...
What could be the problem? How can I solve this and get the value of country from web.config in my aspx page?
Upvotes: 0
Views: 897
Reputation: 35544
It would seem the Visual Studo 2010 editor gets confused about the combination of '
and the inline code <%= ... %>
. Because in Studio 2015 the following line does work:
var country = '<%= System.Configuration.ConfigurationManager.AppSettings["LoginCountry"].ToString() %>';
What you could try is to create the entire line with javascript in code, maybe then the editor is not confused.
<%= "var country2 = '" + System.Configuration.ConfigurationManager.AppSettings["LoginCountry"].ToString() + "';" %>
Or in code behind:
public string javaScript;
protected void Page_Load(object sender, EventArgs e)
{
javaScript = "var country = '" + ConfigurationManager.AppSettings["LoginCountry"].ToString() + "';";
}
and then on the aspx page
function CheckCountry() {
<%= javaScript %>
.... etc
}
Upvotes: 1