Maintaining a value upon submission

I have been struggling with this issue for a few days. Initially, I was confused and looking into using code for a postback and storing my value in a hidden field. However, upon further investigation, it appears that the solution involves simply using a "doSubmit" function when the button is pressed.

The specific value I am attempting to store should only be saved when a particular button is clicked. Since multiple users may be accessing the site concurrently, global storage is not feasible. Perhaps using a cookie could work, allowing me to access the value from my .aspx.cs file.

Here is what I currently have in default.aspx:

<asp:HiddenField id="HiddenValue" value ="" runat="server"/> 
//This may need to be modified to a standard hidden input field

<input name="button1" type="button" class="btn submitter" id="button1" 
value="Copy" title="Create a copy of this id" onclick="SaveId(); doSubmit(); />

function SaveId() {
        $('#<%=hiddenValue.ClientID%>').val("test");
}

Where "test" represents the ID being stored.

The doSubmit function performs a document.form.submit().

Although I am new to aspx and C#, and somewhat inexperienced with JavaScript and jQuery, I can see that the test value gets stored when the doSubmit command is omitted. So, I believe I have that part correct at least. My question now is, what is the best approach to retain my value when submitting this form? Should I use a cookie or is there a more efficient method?

Answer №1

When utilizing web forms like aspx, the entire page is sent back on submission, making it impossible to store information directly on the page. Instead, you must save data on the server side and retrieve it each time the page reloads or use a cookie as mentioned.

I would advise against storing sensitive information in a cookie, unless it is something with high entropy like a GUID. Otherwise, users could easily manipulate the data and pose a security risk.

A good starting point for working with webforms is understanding the page life cycle, a concept not present in MVC frameworks.

To address your query about accessing the Id field across multiple pages, consider storing it in a session on the server side upon submission. Just be cautious, as values stored in session persist throughout the browser tabs and sessions.

Session["Id"] = //your id

var id = (int)Session["Id"]; // retrieving value

If the Id only needs to be accessible within the current page, opt for using ViewState. Keep in mind that ViewState is reconstructed when navigating to another page, resulting in lost stored values.

ViewState["Id"] = //your id

var id = (int)ViewState["Id"]; // getting it back 

In all honesty, if you're new to asp.net, it's recommended to bypass web forms entirely and transition straight into an MVC approach. Web forms are considered limiting by today's standards and can be challenging for beginners, especially when handling complex tasks like dynamic control generation.

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

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Is the custom cursor feature malfunctioning in IE9?

In my form, I have a web browser control that uses a custom cursor in the CSS code. Everything appears to be working fine in IE8. Css Code cursor: url(AppDirectiry\Classes\QClasses\ClsDesignHtml\Cursors\arrow.ani); However, it s ...

What did I miss writing here?

I am currently working on an application using Redux-React. However, I encountered an error while working on my main project files: It seems like your post consists mostly of code; could you please provide more details along with it? It looks like your po ...

Steps for bringing the image to the front and changing the background color to black

I am trying to create a function where a button calls the ID image. However, I want the background div image to be unclickable and for the image to appear in front of all other divs when the page is loading. What CSS style should I add to achieve this? ...

Navigate within an HTML element by utilizing the element's unique ID

I need to create a condition based on the presence of style="display:none;" in the following code snippet. <div class="wrap hide" id="post_query" style="display:none;"> </div> My goal is to identify whether style="display:none;" is included o ...

How can Typescript elevate your use of the IFrame API?

Here is a code snippet that performs the following actions: let doc = this.iframe.contentDocument || this.iframe.contentWindow; let content = `...` doc!.open(); doc!.write(content); doc!.close(); Despite this, the Typescript linter thr ...

Ticket of Authorization (Forms Authentication)

Q1 - The Forms authentication module encrypts its authentication information (ticket) before placing it in a cookie. My limited understanding of encryption algorithms leads me to believe that they typically use a randomly generated value to encrypt and de ...

What is the reason for JsonConvert.DeserializeObject not utilizing the designated JsonConverter?

I have developed a specialized JsonConverter that can be linked to JsonSerializerSettings and utilized with the generic version of JsonConvert.DeserializeObject without any issues: var settings = new JsonSerializerSettings() { TypeNameHandling = TypeN ...

Avoiding type errors in d3 v5 axis by using Typescript

I am new to TypeScript and I have some code that is functioning perfectly. I believe if I define a type somewhere, d3's generics will come into play? Within my code, I have an xAxis and a yAxis. Both are the same, but D3 seems to have an issue with t ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

Is it possible to create a basic calculator with Vue.js by incorporating v-model and possibly v-if?

I am looking to create a Vue.Js component that includes an input field displaying the potential hours saved by a user switching to our software. How can I implement the v-if directive in this scenario? For users spending 20 - 30 hours, they would save 10 ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

What steps should I follow to create a large Angular single page application using ASP.NET MVC?

After gaining some experience with AngularJS on a small project, I am now ready to tackle a larger application. My plan is to create a single-page application using asp.net, making WebAPI calls and loading AngularJS views. However, I am unsure about how ...

Error: Failed to clone an object in Electron due to an unhandled promise

I'm in need of assistance with sending files from the main directory to the renderer. Before proceeding, I attempted to check if it was functioning correctly by using console.log(files). However, this resulted in an error message. Can someone please p ...

Is there another method to retrieve event.target from a React functional component?

Currently, I am creating a form and obtaining input from a mui textfield. I have successfully stored the value of the textfield to a value object. To handle the key and value of the form fields, I have implemented an onValueChanged function. My goal is to ...

In JavaScript, constructors do not have access to variables

Currently, I am attempting to implement Twilio Access Token on Firebase Functions using TypeScript. export const generateTwilioToken = functions.https.onRequest((req, res) => { const twilioAccessToken = twilio.jwt.AccessToken; const envConfig = fun ...

React.js is throwing a 429 error message indicating "Too Many Requests" when attempting to send 2 requests with axios

Currently, I am in the process of learning React with a project focused on creating a motorcycle specifications search web application. In my code file /api/index.js, I have implemented two axios requests and encountered an error stating '429 (Too Ma ...