Javascript 对ClientScript的调用不会保留网页控件中的值

Javascript 对ClientScript的调用不会保留网页控件中的值,javascript,asp.net,clientscriptmanager,Javascript,Asp.net,Clientscriptmanager,我有个小问题。若使用F5刷新页面,TextBox应保留其旧值。在Page_Load()中,如果我继续//加载();然后TextBox1保留其旧值。 一旦我删除了注释,它就会丢失TextBox1中的值 请告诉我背后的原因,以及应该做些什么来避免它 <script type="text/javascript"> function TextBox1_TextChanged() { <% Session["HitCount1"]

我有个小问题。若使用F5刷新页面,TextBox应保留其旧值。在Page_Load()中,如果我继续//加载();然后TextBox1保留其旧值。
一旦我删除了注释,它就会丢失TextBox1中的值

请告诉我背后的原因,以及应该做些什么来避免它

    <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);
        }


    }

函数TextBox1_TextChanged(){
}
函数getMyvalSession(){
var ff=“加载值”;
返回ff;
}
受保护的无效页面加载(对象发送方、事件参数e)
{
//加载();
}
空隙荷载()
{
字符串csname=“OnSubmitScript”;
类型cstype=this.GetType();
//从Page类获取ClientScriptManager引用。
ClientScriptManager cs=Page.ClientScript;
//检查OnSubmit语句是否已注册。
如果(!cs.IsOnSubmitStatementRegistered(cstype,csname))
{
string cstext=“document.getElementById(\“TextBox1\”)。value=getMyvalSession();”;
cs.RegisterOnSubmitStatement(cstype、csname、cstext);
}
}

将内联服务器端代码和代码隐藏代码结合起来通常是个坏主意。我建议只使用代码隐藏代码

此代码:

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

 }
函数TextBox1\u TextChanged(){
}
。。。不会产生将(服务器端)会话项“HITCUNT1”设置为
Textbox1.Text
的效果,因为
Textbox1\u TextChanged
是一个客户端函数,您的赋值语句将在服务器端发生。在运行时,编译器将删除服务器代码块,因此
TextBox1\u TextChanged
将是一个空函数

经验法则:事情发生在客户机上,或者在回发时发生在服务器上,或者通过Ajax调用发生在服务器上。不能将客户端代码和服务器代码混合在一起

我的建议是:改用代码隐藏来完成所有工作。当它工作时,如果有太多回发,请调查Ajax调用