在Javascript中分配textbox的值,并在与C#的会话中设置该值

本文关键字:会话 设置 分配 Javascript textbox 的值 | 更新日期: 2023-09-27 18:20:19

我已经为Javascript/C#问题挣扎了一段时间。我一直在尝试从Javascript中设置一个Session变量。我以前尝试过使用页面方法,但它导致我的javascript崩溃。

在javascript中:

PageMethods.SetSession(id_Txt, onSuccess);

而这个页面的方法:

[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
    Page aPage = new Page();
    aPage.Session["id"] = value; 
    return value;
}

我在这方面没有取得任何成功。因此,我尝试从javascript中设置一个文本框的值,并在c#中放置一个OnTextChanged事件来设置会话变量,但该事件没有被触发。

在javascript中:

document.getElementById('spanID').value = id_Txt;

在html:中

<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server" 
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>

在cs:中

    protected void spanID_TextChanged(object sender, EventArgs e)
    {
        int projectID = Int32.Parse(dropdownProjects.SelectedValue);
        Session["id"] = projetID;
    }

有人知道为什么我的活动都没有被解雇吗?你有我可以尝试的替代方案吗?

在Javascript中分配textbox的值,并在与C#的会话中设置该值

我发现了这个问题,我没有enableSession = true,我不得不使用HttpContext.Current.Session["id"] = value,就像mshsayem所说的那样。现在,我的事件已正确激发,会话变量也已设置。

首先,确保您启用了sessionState(web.config):

<sessionState mode="InProc" timeout="10"/>

第二,确保启用了页面方法:

<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

第三,像这样设置会话值(因为该方法是静态的):

HttpContext.Current.Session["my_sessionValue"] = value;

示例aspx:

<head>
    <script type="text/javascript">
        function setSessionValue() {
            PageMethods.SetSession("boss");
        }
    </script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />

后面的示例代码:

[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
    HttpContext.Current.Session["my_sessionValue"] = value;
    return value;
}
protected void ShowSessionValue(object sender, EventArgs e)
{
    lblSessionText.Text = Session["my_sessionValue"] as string;
}