Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
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.
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()';
Below code perfectly worked for me. I think you are missing namespace.
var apiUrl = '<%= System.Configuration.ConfigurationManager.AppSettings["url"].ToString() %>';
alert(apiUrl);
–
index.html
<input id="getImageUrl" value="@System.Configuration.ConfigurationManager.AppSettings["OPMGTWebUrl"]" style="" />
index.js
var imageUrl = document.getElementById("getImageUrl").value;
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.