2015-11-03 49 views
0

我一直在努力了一段时间,我有一个Javascript/C#的问题。我一直在尝试从Javascript设置一个Session变量。我以前尝试使用页面方法,但它导致我的JavaScript崩溃。在JavaScript中分配文本框的值,并在C中设置值的会话#

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

有没有人有一个想法,为什么没有我的事件,其中的解雇?你有可以尝试的替代解决方案吗?

+1

内的静'WebMethod',使用'HttpContext.Current.Session [ “ID”] =值;' – mshsayem

+1

一个常见的劈:将一个隐藏的asp按钮( 'display:none')和一个隐藏字段。隐藏按钮的“OnClientClick”,设置隐藏字段。在“OnClick”处理程序(cs)中,从隐藏字段中读取值。调用js'$(“#buttonId”)。click()'来触发事件。 – mshsayem

回答

1

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

1

首先,确保你的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; 
}