Working with Asp.Net variables in c#

Variables don’t automatically maintain state across page calls in ASP.NET. Asp.Net Page has a life cycle and being stateless, the information is lost at the end of this cycle, after a request has been served on the client side. One way is to use View-state for the persistence of the variables, but this significantly increases the size of a page and the data sent and received, making it slow. There are several solution for this.

  • SessionState
  • hidden fields
  • querystrings
  • Here is SessionState example

    // saving aHiddenVariable 
    // retreiving aHiddenVariable 
    string aHiddenVariable = (string)Session["aHiddenVariable"];

    Here is hidden field example.

    In HTML, we simply need to create:

    <input type="hidden" id="aHiddenVariable">

    To set it’s value in javascript:

    document.getElementById("aHiddenVariable").value = "myValue"

    In ASP.NET code-behind, you use the Request object to retrieve the value.

    string aHiddenVariable= (string)Request.Params["aHiddenVariable"];

    Here is a sample for QueryString

    // setting quesryString
    // set s=feed, "text" to search
    // retrieve variable
    string textToSearch= Request.QueryString["s"];