Reputation: 169
I am trying to read apiUrl key value from web.config file so that I can take advantage of the .net transform config to manage deployment in different environments. Here is my Webconfig code:
<appSettings>
<add key="url" value="http://localhost:6299/api/"
</appSettings>
and in the plain js file I have this code:
var apiUrl = '<%=ConfigurationManager.AppSettings["url"].Tostring()
%>'.
It is not giving the url value. How can I read web.config value in javascript file?
Upvotes: 16
Views: 88213
Reputation: 1031
Complementing freedomn-m's answer, doesn't seem possible to do it from within the js file directly.
So my solution was to access the configuration from the cshtml and pass it to the js script as a parameter.
I used the first method here to pass arguments
So my code looked something like this:
My cshtml file
<script id='my-unique-id'
my-arg='@System.Configuration.ConfigurationManager.AppSettings["MY_KEY"]'>
src='test.js'
</script>
My 'test.js' file
const myArg = document.GetElementById('my-unique-id').getAttribute('my-arg');
Upvotes: 0
Reputation: 11
index.html
<input id="getImageUrl" value="@System.Configuration.ConfigurationManager.AppSettings["OPMGTWebUrl"]" style="display:none" />
index.js
var imageUrl = document.getElementById("getImageUrl").value;
Upvotes: 1
Reputation: 1
The following line will return the URL
value.
var apiUrl = '<%=ConfigurationManager.AppSettings["url"]%>';
Upvotes: -3
Reputation: 121
Below code worked for me in ASP.Net webforms application, but not in MVC application
var key = '<%= System.Configuration.ConfigurationManager.AppSettings["key"].ToString() %>';
for MVC application in .cshtml page try below
var key = '@System.Configuration.ConfigurationManager.AppSettings["key"].ToString()';
Upvotes: 12
Reputation: 406
Below code worked for me.
<script>
var apiUrl = '@System.Configuration.ConfigurationManager.AppSettings["url"]';
</script>
Upvotes: 16
Reputation: 28611
"In the plain js file"
do you mean a file ending in .js ?
.js files are not parsed server-side so the <%=
values are not converted. This works for the other answer ("worked for me") as they will have it in the .aspx/.cshtml file rather than a 'plain .js file'.
You'll need to move your code to your .aspx/.cshtml or you'll need to pass the url value in to your js (eg) via a function parameter from the .aspx/.cshtml file.
Upvotes: 18
Reputation: 551
Below code perfectly worked for me. I think you are missing namespace.
var apiUrl = '<%= System.Configuration.ConfigurationManager.AppSettings["url"].ToString() %>';
alert(apiUrl);
Upvotes: 2