Tips for transferring a text from asp.net code behind to local web storage

Is there a way to pass a string from C# code-behind to local storage using JavaScript?

I attempted to pass the string through a HiddenField and Session cache, but was unsuccessful in retrieving the string in JavaScript to store it in local storage. I have an onclick function in C# that receives the string and writes it to the session cache. Then, I try to retrieve the string using a JavaScript function that reads the session cache and writes it to local storage. However, the result is always empty, except when I manually fill the session cache with a static string within the page load function.

Could anyone identify any issues with my solution or offer suggestions?

I welcome any input you may have.

Edit:

I click Button "btn1" to write myString into the hidden field and then click "btn2" to read it in JavaScript and store it in local storage.

HTML code

<asp:HiddenField ID="hiddenVar" runat="server" ClientIDMode="Static" />

<asp:Button ID="btn1" runat="server" OnClick="writeInHiddenField" />
<asp:Button ID="btn2" runat="server" OnClientClick="writeHfInLS()" />

<script>
  function writeHfInLS() { window.localStorage.setItem('key', document.getElementById("hiddenVar").value); }
</script>

C# function in code behind

writeInHiddenField() { hiddenVar.Value = myString; }

Answer №1

For handling a hidden field, you can utilize an asp:HiddenField if working with web forms:

<asp:HiddenField ID="LocalStore" runat="server" ClientIDMode="Static" />

To access the value, you can use the following JavaScript code:

document.getElementById("LocalStore").value

Alternatively, with JQuery, you can retrieve the value like this:

$("#LocalStore").val();

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

Splitting the div into two columns

I've encountered various solutions to this issue, but when I integrate an Angular2 component inside the divs, it fails to function properly. Here is my progress so far: https://i.stack.imgur.com/qJ8a9.jpg Code: <div id="container"> <div ...

Instructions for capturing multi-dimensional arrays using forms in Vue

I have a snippet of code that looks like this: <div class="form-item"> <label for="list-0"><?php _e('List 0', 'test'); ?></label> <input name="list[0]" type="text" id="list-0" value=""> </div> &l ...

Creating a navbar that sticks to the top of the page

I've been working on some code to create a sticky navbar that remains fixed as I scroll down, but unfortunately, it's not working. I suspect the issue might lie in the CSS, as the HTML and javascript seem fine. Interestingly, this same code has w ...

Mastering Chaos in the New Year: HackerRank Practice Problem - Optimizing C# Solutions

static void minimumBribes(int[] arr) { Int32 totalCount = 0; bool success = true; Int32[] size = Order(arr); for (int i = 0; i < arr.Length; i++) { Int32 tempVar = 0; Int32 chaotic = 0; Int32 index = FindIndex ...

The collection has been altered; iteration action may not be performed in MVC

I keep encountering this issue: Collection was modified; enumeration operation may not execute protected void SendAddedMessages(IEnumerable<int> receiverIds, Result result) { foreach (var receiverId in receiverIds) { SendAddMessage(r ...

Encountering an issue where props are receiving a value of undefined within a component that is

After receiving a JSON response from getStaticProps, I double-checked the data by logging it in getStaticProps. The fetch functionality is working smoothly as I am successfully retrieving the expected response from the API. import Layout from '../comp ...

When using ng-repeat in Angular JS, only the first element will be displayed on the

I am currently utilizing Angular 1.5.5 function RetrieveDashboardDataForAllEmployees() { var response = eRotaService.RetrieveDashboard(); response.then(function (data) { $scope.weekDays = data.data; console.log(data.data); }, ...

Retrieving the value of a field using its name within a Meteor template

I have two variables in my template rows and fields storing the documents and field names in the collection, respectively. I display it using {{#each rows}} <tr> {{#each fields}} <td>{{name}}</td> {{/each}} </tr> ...

Combining Array Elements to Create Overlapping Images in JavaScript

My goal is to create a planner where users can choose a wallpaper based on the season. Right now, I'm focusing on fall, and when you click on fall, you can see all the different wallpapers (each URL from my array is displayed). However, once the alert ...

Error in JavaScript: addition of all numbers not functioning properly within a loop

After attempting to sum all the numeric values within the result[i].quantity array using += or dataset.quantity = 0 + Number(result[i].quantity);, I encountered issues where the console.log was returning either NaN or the value from the last iteration like ...

Add content to div element using input from textarea

I'm attempting to create a basic text editor where users can input text and by clicking the edit button, it will add that text to the end of the id="textArea". However, nothing happens when I click the edit button after entering text in the textarea. ...

The Request.QueryString cannot be identified due to System.Web being included in the namespace

Having a simple question regarding retrieving the hostname from a URL in my ASP.NET project. I've encountered this issue twice and need some guidance. The code for retrieving the hostname is not within a web page but rather inside a class that is par ...

The active tab will dynamically update, however, clicking anywhere on the page will always bring you back to the first tab as

My view includes the following tabs: <div class="tabbable"> <ul class="nav nav-tabs padding-18"> <li class="active"> <a aria-expanded="false" data-toggle="tab" href="#Tab1"> <i class="green ac ...

Utilize TxTextControl to insert an image into a Dotnet document

I'm new to using TXTextControl and currently working with version 24. I am looking to incorporate an image from the client's local system into the document. I have already written the necessary JavaScript code for uploading the file. The JS sc ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

I am having trouble with CSS, JS, and image files not loading when using Angular 9 loadChildren

I am facing an issue with loading CSS, JS, and images in my Angular 9 project. I have separate 'admin' and 'catalog' folders where I want to load different components. However, the assets are not loading properly in the 'catalog&ap ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

Troubleshooting error message: "Unsupported import of ESM Javascript file in CommonJS module."

My project relies solely on CommonJS modules and unfortunately, I cannot make any changes to it. I am attempting to incorporate a library that uses ESM called Got library (https://github.com/sindresorhus/got). This is the snippet of my code: const request ...

Exploring the Magic of ES6 Object Destructuring

Learning about ES6 destructuring is still new to me. I have encountered a scenario where I need to extract specific values from a nested object within an object. For instance - z = {g: 1, h: 2, i: {d1:5, d2:6, d3:7}} When attempting to destructure with ...

Looking to trigger a JavaScript function upon clicking a Stacked Column Chart

Currently, I am utilizing the Highcharts Demo - Stacked column for my project. You can view it at this link: http://www.highcharts.com/demo/column-stacked . What I need is that when a user clicks on one of the columns, I want to trigger a JavaScript func ...