0

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:

enter image description here

what am I missing please? Thanks for any replies

4
  • use cookie, OR: you can do in configuration json set application variable. OR on application start Application["variablename"] = "hello"; and to read: HttpContext.Application["variablename"].ToString(); Commented Apr 13, 2024 at 3:19
  • i think this thread would be helpful stackoverflow.com/questions/49624242/… Commented Apr 13, 2024 at 3:21
  • Hi thanks for reply, yes setting or declaring the value in #C is ok but how do I retrieve it in the js file when I need it? Commented Apr 13, 2024 at 16:08
  • stackoverflow.com/questions/16474640/… Commented Apr 13, 2024 at 23:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.