Call to ClientScript doesnot preserve value in Controls of Web Page

153 Views Asked by At

I have a small problem . If page is refreshed using F5 , TextBox should preserve its old value . In Page_Load() , if i keep // Loading(); then TextBox1 preserve its old value.
As soon as i remove comment , it loose value in TextBox1 .

Please tell me the reason behind it and What should be done to avoid it .

    <script type="text/javascript">

      function TextBox1_TextChanged() {
       <%
           Session["HitCount1"] = TextBox1.Text ;
       %>

     }

     function getMyvalSession() {
            var ff = "Loading Value";
           return ff;
     }

    </script>

<body>
    <form id="form1" runat="server">

    <asp:TextBox ID="TextBox1"  Name="TextBox1"  runat="server" 
 AutoPostBack='true'  onchange="TextBox1_TextChanged()"></asp:TextBox>

          <%
                 string x = null;
                  x = Session["HitCount1"].ToString().Trim();

                  if ((x.Equals(null)) || (x.Equals("")))
                 { 
                     // Session Variable is either empty or null .
                 } 
                 else 
                 {
                     TextBox1.Text = Session["HitCount1"].ToString();
                 }
          %>

  </form>
</body>

    protected void Page_Load(object sender, EventArgs e)
    {
      //  Loading();
    }

    void Loading()
    {
        String csname = "OnSubmitScript";
        Type cstype = this.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = Page.ClientScript;

        // Check to see if the OnSubmit statement is already registered.
        if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
        {
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession()  ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
        }


    }
1

There are 1 best solutions below

0
On

Combining inline server-side code and code-behind code is generally a bad idea. I would recommend just using the code-behind code.

This code:

  function TextBox1_TextChanged() {
   <%
       Session["HitCount1"] = TextBox1.Text ;
   %>

 }

... is not going to have the effect of the (server-side) Session entry "HitCount1" getting set to Textbox1.Text, because TextBox1_TextChanged is a client-side function, and your assignment statement is going to happen on the server side. At run time, the chunk of server code will have been removed by the compiler, so TextBox1_TextChanged will be an empty function.

The rule of thumb: Things happen on the client, or they happen on the server on postback, or they happen on the server via Ajax calls. You can't mix client and server code together.

My recommendation: switch to doing everything in code-behind. When you have it working, if you have too many postbacks, investigate Ajax calls.