Just learning/diving into a cshtml and razor application so please bear with.
We have an MVC razor front end UI application which calls a C# API back end application.
Currently the URL for the API is set in one of the js files, example apiCalls.js
This file is then added as a reference to the bottom of the page1.cshtml page with:
@Html.Script(Url.WidgetContent("~/Custom/Scripts/apiCalls.js"), "bottom")
This all works fine, and an AJAX call is made on the apiCalls.js page to retrieve data from the API.
However, I would like the API url to be set in the C# side, currently it is set in the apiCalls.js, and used when needed for AJAX
I have found a few similiar topics: https://www.codeproject.com/Questions/671106/How-can-i-declare-global-variable-to-use-all-mvc-v and the accepted answer here: Access Session variables in JavaScript
but it isnt working.
So in global.asx.cs I am adding:
private void PagePreRenderCompleteEvent(IPagePreRenderCompleteEvent evt)
{
HttpContext Context = HttpContext.Current;
if (Context != null && Context.Session != null)
{
Session["apiURL"] = "https://www.123.com";
}
}
then at the top of apiCalls.js I am replacing the current
var api = 'www.api123.com';
with
console.log('api START');
var api = '@Session["apiURL"]';
console.log('apiEndPoint END ' + api);
but I can see from the comments in the console that:
apiEndPoint START
apiEndPoint END @Session["apiURL"]
obviously this is because its a string, but why is the accepted answer I mentioned like so:
what am I missing please? Thanks for any replies
