Utilize JavaScript to capture the value of a textbox and then store this value in a session using C#

I've been facing a problem for some time now related to setting a Session variable from Javascript in a C# environment. I attempted to use page methods previously, but it ended up causing my Javascript code to crash.

Here's the snippet of Javascript code I used:

PageMethods.SetSession(id_Txt, onSuccess);

And here's the corresponding page method in C#:

[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
    Page aPage = new Page();
    aPage.Session["id"] = value; 
    return value;
}

Unfortunately, this approach didn't work for me. So, I then tried setting the value of a textbox using Javascript and included an OnTextChanged event in my C# code to set the session variable. But it seems like the event is not triggering.

In the Javascript code:

document.getElementById('spanID').value = id_Txt;

The HTML part looks like this:

<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server" 
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>

In the C# code behind:

protected void spanID_TextChanged(object sender, EventArgs e)
{
    int projectID = Int32.Parse(dropdownProjects.SelectedValue);
    Session["id"] = projetID;
}

I'm puzzled as to why none of my events are being triggered. Does anyone have any insights on this issue or perhaps an alternative solution that I could experiment with?

Answer №1

Hooray! I finally pinpointed the problem: it turns out that setting enableSession = true and utilizing

HttpContext.Current.Session["id"] = value
as advised by mshsayem resolved the issue. Consequently, my event is now triggering correctly and the session variable is successfully established.

Answer №2

Before proceeding, it is essential to ensure that sessionState is enabled in the web.config file:

<sessionState mode="InProc" timeout="10"/>

Next, verify that page-methods are enabled by adding the following code snippet:

<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

To set a session value using a static method, use the following syntax:

HttpContext.Current.Session["my_sessionValue"] = value;

Sample implementation in an aspx file:

<head>
    <script type="text/javascript">
        function setSessionValue() {
            PageMethods.SetSession("boss");
        }
    </script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />

Sample code behind for handling session values:

[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
    HttpContext.Current.Session["my_sessionValue"] = value;
    return value;
}

protected void ShowSessionValue(object sender, EventArgs e)
{
    lblSessionText.Text = Session["my_sessionValue"] as string;
}

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

A guide on implementing React hooks within a React class component

Just stepped into the JavaScript world and facing a bit of trouble... Currently, I'm working with a React hook import { useKeycloak } from '@react-keycloak/web'; import { useCallback } from 'react'; export const useAuthenticatedCal ...

Swapping out innerHtml in place of appending

I'm having an issue with my table setup. The first row serves as a label and dropdown for selecting the number of spaces. When I select a new number from the dropdown, additional rows are appended instead of replacing the previous ones. How can I ensu ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

Refreshing a Blazor Server page results in a blank screen when rendering the page from a Razor Library

Currently, I am working on an ASP.NET Core 8.0 Blazor application where I want to create a separate Razor library for shared screens and components that can be used in a .NET Maui app as well. I successfully added the assembly to the router using Addition ...

In ASP.NET and WCF, what is the best way to verify the identity of the application making a request, rather than the user making

Due to various reasons, the group I am working with prefers not to utilize certificates and is opposed to a service that can be accessed by anyone with a valid login. I am wondering how I can authenticate an application as an authorized application design ...

Creating a dropdown menu within a <span> element with JavaScript

Snippet of HTML: <body onload="init();firstInit();"> Snippet of JavaScript: function init(){ var tb = new Ext.Toolbar({ renderTo: 'toolbar', height: 25 }); var ht='<table><tr>'; ht+='<td>&apo ...

During the iteration of the foreach loop in the aspx page, the error CS1026 is encountered

I encountered a compiler error (CS1026: ) expected) in the code snippet below at this line: "position": <%=node.Attribute("level").Value;%>, Here is the full code: <script type="application/ld+json"> {"@context": "http://schema.org", "@type" ...

Creating an object structure in React Native based on existing data sources

I've encountered a unique object structure within a specific library that looks something like this: const libraryTemplateData = [ { eventContainerStyle: { style: { opacity: 1, }, }, ...

Using Confluence to Access a Unique REST API

I've successfully developed and deployed my own webservice using WCF C#. Now, I'm looking to utilize JavaScript to call this service, retrieve data from it, and display it on a chart. Below is the code snippet that I placed within a custom HTML ...

The non-null assertion operator seems to be failing to function properly

Error during runtime: Issue with reading property 'id' of an undefined element if (!this.havingMultipleProjects) {//checking for only one project or none at all if (this.authenticationProvider.member.projects != null) this.projectProvider ...

Error: Unable to locate module: Issue discovering 'crypto' and 'fs' modules

I am currently in the process of learning React and attempting to establish a connection between my React app and my database using the following code: var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: ...

Using JavaScript in conjunction with IPFS to verify the 404 status from localhost:8080 and identify if the local IPFS node is active within a browser user script

As a newcomer to IPFS and JavaScript, I have successfully created a simple IPFS userscript that redirects addresses containing *://*/ipfs/* or *://*/ipns/* to http://localhost:8080/<IPFS_HASH>. However, there is an issue when the local IPFS node is ...

Invoke a JavaScript function with arguments upon clicking on a hyperlink

Struggling to generate code for an href tag with a JavaScript function that takes parameters - a string and an object converted into a json string. My initial attempt looked like this: return '<a style="text-decoration:underline;cursor:pointer" ta ...

Utilizing a JavaScript variable in Firefox with Java WebDriver: A guide

The main objective is to retrieve the JavaScript element authKey in Java code. Below are the codes: index.html: ... <script type="text/javascript"> var params = { authKey: "abc" }; Main.init("#content", p ...

Ways to monitor and record all outgoing requests in NodeJS/Express

I'm currently conducting a study on logging outbound requests within a NodeJS/Express application. What methods exist to capture and log all requests originating from the web application? This includes fetch() requests, as well as calls like <img ...

Capturing form submission events in JavaScript and determining the specific form that triggered the submission

Is there a way to intercept form submits from webpages that are not under my control? The approach I am currently using involves looping through all form objects during onLoad and modifying the onsubmit event handler. However, I am facing an issue where I ...

Displaying a meager 0.5% on the BootStrap progress indicator

Utilizing the bootstrap progress bar to display the percentage of a person's miles covered out of a total of 23,872 miles. Take user A as an example, they have covered only 5 miles: 5/23872 = 0.00020945 * 100 = 0.02094504 miles. Currently, anything ...

Strategies for developing versatile controls that can adapt to the environment in which they are used?

Take a look at the image provided. In my application, I have three large black rectangles representing different forms in separate contexts. Across all three forms, there is a red box control present. The visibility and values of this red box are determin ...

Performing type validation on dynamically loaded assemblies at runtime

I am currently experiencing an issue when utilizing external dlls with mono during runtime. Let's say we have a framework dll that consists of an interface called IMyInterface, and a "plugin" project which utilizes this framework by implementing the I ...

The property 'first' cannot be accessed in null value

Currently, I am in the process of creating a Discord bot that performs specific actions when someone types !true @USER [Location]. The desired behavior is to send a direct message to the mentioned user, assign a role, and change their nickname to [Location ...