Tech
Forums
Jobs
Books
Events
Videos
Live
More
Interviews
Certification
Training
Career
Members
News
Blogs
Contribute
An Article
A Blog
A Video
An Ebook
An Interview Question
Register
Login
4
Answers
session and cookies in mvc5
Aleena Saviour
7y
239
1
Reply
I have lost data in session/cookies when I call the action of controller second time.what is the reason of this problem?
my code is given below...
[HttpPost]
public
ActionResult AddCart(
long
productId,
double
Qty,
decimal
price)
{
decimal
TotAmount = 0;
long
userId = 0,OrderId=0;
string
status =
"incart"
;
DataTable dt =
new
DataTable();
try
{
//var session = HttpContext.Session;
//if (session["orderid"] != null)
//{
// OrderId =Convert.ToInt64(session["orderid"].ToString());
// TotAmount = Convert.ToDecimal(session["orderAmt"]);
//}
HttpCookie myCookie = Request.Cookies[
"order"
];
if
(myCookie !=
null
)
{
OrderId =Convert.ToInt64(myCookie.Values[
"orderid"
]);
//Response.Write("
" + myCookie.Name + "
" + myCookie.Value);
}
TotAmount = TotAmount + price;
SqlCommand cmd =
new
SqlCommand(
"OrderSave"
, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(
"@PKOderId"
, OrderId);
cmd.Parameters.AddWithValue(
"@PKUserId"
, userId);
cmd.Parameters.AddWithValue(
"@TotAmount"
, TotAmount);
cmd.Parameters.AddWithValue(
"@Status"
, status);
cmd.Parameters.AddWithValue(
"@FKRowStatusId"
, 1);
cmd.Parameters.AddWithValue(
"@TimeStamp"
, DateTime.Now);
con.Open();
SqlDataAdapter da =
new
SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
if
(dt.Rows.Count>0)
{
OrderId = Convert.ToInt64(dt.Rows[0][
"PKOrderId"
].ToString());
userId= Convert.ToInt64(dt.Rows[0][
"PKUserId"
].ToString());
TotAmount= Convert.ToDecimal(dt.Rows[0][
"TotalAmount"
].ToString());
long
cartid = 0;
SqlCommand cmdcart =
new
SqlCommand(
"AddCart"
, con);
cmdcart.CommandType = CommandType.StoredProcedure;
cmdcart.Parameters.AddWithValue(
"@PKCartId"
, cartid);
cmdcart.Parameters.AddWithValue(
"@PKOrderId"
, OrderId);
cmdcart.Parameters.AddWithValue(
"@PKProductId"
, productId);
cmdcart.Parameters.AddWithValue(
"@Quantity"
, Qty);
cmdcart.Parameters.AddWithValue(
"@FKRowStatusId"
, 1);
cmdcart.Parameters.AddWithValue(
"@TimeStamp"
, DateTime.Now);
con.Open();
cartid = Convert.ToInt64(cmdcart.ExecuteScalar());
con.Close();
if
(cartid>0)
{
//session.Add("orderid",OrderId.ToString());
//session.Add("orderAmt",TotAmount.ToString());
HttpCookie order =
new
HttpCookie(
"order"
);
order.Values[
"orderid"
] = OrderId.ToString();
// Add the cookie.
Response.Cookies.Add(order);
status =
"success"
;
}
bool
sess= Session[
"orderid"
]!=
null
?
true
:
false
;
}
}
catch
(Exception ex)
{
Console.WriteLine(ex);
status =
"failed"
;
}
return
Json(status,JsonRequestBehavior.AllowGet);
}
The boolean sess gets value of session...but in next postback the session/cookie returns null.
Post
Reset
Cancel
Answers (
4
)
Next Recommended Forum
Globalization Localization Asp Net MVc
Sorttop 10 Record Based on date in descending order