我需要通过使用 jQuery 调用 PageMethod 来设置几个 session 变量。
客户端js如下所示:
function setSession(Amount, Item_nr) {
//alert(Amount + " " + Item_nr);
var args = {
amount: Amount, item_nr: Item_nr
}
//alert(JSON.stringify(passingArguments));
$.ajax({
type: "POST",
url: "buycredit.aspx/SetSession",
data: JSON.stringify(args),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('Success.');
},
error: function () {
alert("Fail");
}
});
}
服务器端是这样的:
[System.Web.Services.WebMethod(EnableSession = true)]
public static void SetSession(int amount, int item_nr)
{
HttpContext.Current.Session["amount"] = amount;
HttpContext.Current.Session["item_nr"] = item_nr;
}
只是, session 变量似乎没有设置。当我尝试 Response.Write 输出 session 变量时,我什么也没得到。我没有收到任何错误,并且我可以提醒从 onclick 事件传递到 js 函数的值,因此它们就在那里。
有人可以看看我是否错过了什么吗?
谢谢
最佳答案
您在 session 中没有得到任何内容,因为 null 被传递给 webmethod,请使用调试器单步执行您的 javascript 和 c# 以查看其来自何处。
您发布的代码看起来没问题,因为我设法让它在快速测试页面中工作,所以问题出在您代码的其他位置。这是我的测试代码,希望对您有所帮助。
jquery:
$(document).ready(function () {
$('#lnkCall').click(function () {
setSession($('#input1').val(), $('#input2').val());
return false;
});
});
function setSession(Amount, Item_nr) {
var args = {
amount: Amount, item_nr: Item_nr
}
$.ajax({
type: "POST",
url: "buycredit.aspx/SetSession",
data: JSON.stringify(args),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('Success.');
},
error: function () {
alert("Fail");
}
});
}
html:
<div>
Input1: <input id="input1" type="text" />
<br />
Input2 <input id="input2" type="text" />
<br />
<a id="lnkCall" href="#">make call</a>
<br />
<asp:Button ID="myButton" runat="server" Text="check session contents" onclick="myButton_Click" />
<br />
<asp:Literal ID="litMessage" runat="server" />
</div>
c#
[System.Web.Services.WebMethod(EnableSession = true)]
public static void SetSession(int amount, int item_nr)
{
HttpContext.Current.Session["amount"] = amount;
HttpContext.Current.Session["item_nr"] = item_nr;
}
protected void myButton_Click(object sender, EventArgs e)
{
litMessage.Text = "ammount = " + HttpContext.Current.Session["amount"] + "<br/>item_nr = " + HttpContext.Current.Session["item_nr"];
}
关于jquery - 在 PageMethod (asp.net) 中设置 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5554718/