Looking for a way to access session values in JavaScript? If your JavaScript code is located in the code behind of an ASP.NET application, you may be wondering how to retrieve and set variable values

Struggling to retrieve the session value in my asp.net code behind using JavaScript. The syntax seems incorrect and I cannot figure out how to access the session value.

I attempted to invoke JavaScript on page load, which worked without issues. However, when trying to assign the variable value as a session value, the alert box is not being triggered. It appears that I made an error somewhere, but I am unsure of what it might be.

Below is the snippet from the code behind:

str += "<script type='text/javascript'>" +
             //"alert('testing');" +
            "var sesindex = '<%=Session["indexval"]%>';" +
                "alert(sesindex);" +

                 "</script>";

My objective is to set the value of sesindex and display it in an alert box. Even though it works fine on an HTML page, the functionality fails within the code behind.

Answer №1

Not a huge fan of this solution, but it might work for inserting values into a string.

var sessionValue = Session[indexValue];

string += "<script type='text/javascript'>" +
        $"var sessionIndex = '{sessionValue==null?"":sessionValue.ToString()}'" +
            "alert(sessionIndex);" +"</script>";

This method will handle cases where the value is null. You can learn more about $"{}" here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ADFS C#.NET Web Forms App triggers a Windows authentication dialog box to prompt for further user authentication

After updating a legacy 4.5 C#.NET webforms app to use ADFS for authentication, I encountered an issue where having Windows authentication enabled in IIS caused a second login prompt to appear after signing into the ADFS server. Disabling Windows authentic ...

Error in executing a function within an asynchronous function sequence

Whenever a user logs in, I want to update their data in Firestore. However, the code I am using does not seem to work as expected. It fails to create a custom User object from the firebase.User. Can anyone help me understand why this is happening and how ...

Is it considered poor form to send as many as 100 ajax requests when loading a webpage?

My table can display up to 100 rows, sometimes even more. Is it considered a bad practice to loop through all these rows and send an AJAX post request to fetch data? I am hesitant to do this during the page load as it may significantly slow down the loadin ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: https://i.sstatic ...

"Fixing the Vertical Order of Divs with Jquery: A Step-by-

Before I completely lose my mind, I need some help with a coding issue. Right now, I have two initial divs displayed. The user should be able to add these divs below the original ones as many times as they want, or remove them if needed. I've been att ...

Cross-origin resource sharing problem encountered in Firefox and Internet Explorer, while functioning properly in Chrome

I am encountering CORS errors in Firefox and IE, but everything is functioning properly in Chrome. The two requests causing the issue are A general call to Facebook which works in Chrome and Firefox, but fails in IE 11. I am making a request to verify t ...

When attempting to execute "nodemon," the command was not detected

When trying to use 'nodemon' in the command line, an error occurs stating that it is not recognized as a cmdlet, function, script file, or operable program. The system suggests checking the spelling of the name and verifying that the path is corr ...

injecting javascript dynamically using jquery

I am attempting to conditionally load a script in the case that the browser being used is IE8. To achieve this, I have employed jQuery's .getScript function as it allows me to execute certain actions after the script has been loaded. The issue lies in ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

How can I implement a scroll functionality to navigate to the next item in a Vuetify v-carousel?

I'm currently working on a front page layout using the v-carousel component and I am looking to achieve automatic scrolling to the next item without the need for arrows or delimiters. How can I make this happen? Below is my current code: <template ...

Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to ...

The duplication of printed keys and values from a JavaScript object is causing issues

I am working with a JSON object structured like this: var data = { "2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"], "2020-01-21": ["08:00 - 09:00"] }; My objective is to display each value along with its corresponding key in a list format, as follow ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

Highlight main title in jQuery table of contents

I have successfully created an automatic Table of Contents, but now I need to make the top heading appear in bold font. jQuery(document).ready(function(){ var ToC = "<nav role='navigation' class='table-of-contents vNav'>" + ...

HTML and JavaScript: Struggling to include multiple parameters in onclick event even after escaping quotes

I am struggling to correctly append an HTML div with multiple parameters in the onclick function. Despite using escaped quotes, the rendered HTML is not displaying as intended. Here is the original HTML code: $("#city-list").append("<div class='u ...

Creating a visually appealing chart similar to Excel can be achieved using JavaScript with a whopping 64382 lines of JSON data. No need for Chart.js or any additional tools - simply rely on JavaScript, HTML, and CSS to

I have a project that is due in just a few hours and I need to create a detailed chart using a large set of 64382 lines of JSON data. My knowledge of javascript is limited, so I am struggling to come up with ideas on how to approach this task. While I have ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

What is the best way to save and reload a canvas for future use?

My current setup involves using PDF.js to display PDF documents in a web browser. The PDF.js library utilizes canvas for rendering the PDF. I have implemented JavaScript scripts that allow users to draw lines on the canvas by double-clicking, with the opti ...

Jest's expect.any(Object) function is not able to match CancelToken

After converting some files in a project to TypeScript, I encountered a test failure related to the following code: expect(mocks.request).toHaveBeenCalledWith({ headers: { 'Content-Type': 'bar' }, method: 'put', params: ...

The angular service for testing with Jasmine encountered an issue as it was unable to locate an object to spy on in order to test

I'm relatively new to writing unit tests for services in Angular using Jasmine. I am currently working on a service that has a simple get method returning an Observable, and I need to retrieve the URL from another file called ApiEndpointsConfig. Howev ...