在没有回发的情况下更新textbox_change上的会话变量

时间:2013-05-14 14:21:59

标签: asp.net

有没有办法将文本框文本保存到会话变量而不必回发文本更改?

1 个答案:

答案 0 :(得分:2)

您需要分四个阶段完成此操作。

1)在文本框中添加onkeydown="textChanged(this.ID);"

2)使用一些Javascript来捕获文本

3)触发对Web方法的Ajax调用

4)使用web方法存储会话变量。

这样的事情:

在您的文本框中,设置Autopostback=false,这样就不会在回信时回复。

创建一个小的Javascript函数,当用户输入时将触发该函数。

此功能将首先清除附加到文本框的任何计时器。然后它将创建另一个将在1秒后触发另一个函数。这将确保您不会过于频繁地触发结束功能。

 function textChanged(id) {
        var txtBox = document.getElementById(id);
        clearTimeout(txtBox.timer);
        txtBox.timer = setTimeout('SaveVariable()', 1000);
    };

1秒后,您的方法将调用以下内容:

function SaveVariable(){
       // Do an ajax call in here and send your textbox value to a web method
        var t = // GetYourTextboxTextHere
        if (t != "") {
            $.ajax({
                type: "POST",
                url: "yourPage.aspx/SaveMyTextVar",
                data: "{'textToSave ': '" + escape(t) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if (!msg.d) {
                        // it didn't save
                    } else {
                        // it saved just fine and dandy
                    };
                }
            });
        };
}

最后,在您的代码背后捕获文本的小型Web方法

<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> <Services.WebMethod()> _
Public Shared Function SaveMyTextVar(ByVal textToSave As String) As Boolean
         '' Save your variable to session here.
         '' return true or false
         '' you can capture the returning result in the AJAX that calls this method
End Function