I need to set a couple of Session vars by calling a PageMethod using jQuery.
The client side js looks like this:
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");
}
});
}
and the server side like this:
[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;
}
only, it seems that the Session vars are not set. When I try to Response.Write out the Session vars, I get nothing. I get no errors, and I can alert out the values passed from the onclick event, to the js function, so they are there.
Can anyone see if I missed something?
Thnx
Your not getting anything in your session because a null is being passed to the webmethod, use a debugger to step through your javascript and c# to see where its coming from.
The code you posted seems ok as I managed to get it working in a quick test page, so the problem is else where in your code. Here's my test code, hope it helps.
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"];
}