Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read key value from web.config in javascript file?

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?

like image 913
valmatic Avatar asked Jun 27 '15 17:06

valmatic


People also ask

How read config file in JavaScript?

var Server = require('mongodb'). Server; var MongoDB = require('mongodb'). Db; var dbPort = readConfig(dbPort); var dbHost = readConfig(dbHost); var dbName = readConfig(dbName);

How do you access Appsettings in JavaScript?

It is not possible to read the AppSetting value directly in JavaScript and hence using JavaScript XmlHttpRequest (XHR), an AJAX call will be made to a WebMethod which will read the AppSetting value and return it to the JavaScript function.

What is config JavaScript?

Config. js allows developers to configure their applications in an XML block instead of hard-coding values inside their scripts or in JSON objects. The XML can be embedded inside an HTML document or in a separate XML file. The configuration block may contain strings, numbers, arrays and HTML.


1 Answers

"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.

like image 98
freedomn-m Avatar answered Sep 19 '22 20:09

freedomn-m