如何在会话变量中存储数据? [英] How to store data in a session variable?
问题描述
如果您可以在会话中存储user_id,我正在写信寻求建议。
执行下面的方法(add_to_cart())时,会在下面的行中抛出以下错误:
I am writing to seek advice, if you can store a user_id in a session.
when execute the below method (add_to_cart()), it throws the following error on the line below:
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'.
List<String> cart = new List<String>();<br />
cart = (List<string>)Session["UserAuthentication"];
protected void AddToCart_Click(object sender, EventArgs e)
{
var selectedProducts = GridView1.Rows.Cast<GridViewRow>()
.Where(row => ((CheckBox)row.FindControl("SelectedProducts")).Checked)
.Select(row => GridView1.DataKeys[row.RowIndex].Value.ToString()).ToList();
if (Session["UserAuthentication"] == null)
{
Session["UserAuthentication"] = selectedProducts;
}
else
{
// string SessionData = Session["UserAuthentication"].ToString();
List<String> cart = new List<String>();
cart = (List<string>)Session["UserAuthentication"];
foreach (var product in selectedProducts)
cart.Add(product);
Session["UserAuthentication"] = cart;
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("SelectedProducts");
if (cb.Checked)
cb.Checked = true;
try
{
{
insert_port();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
这个错误可能与数据有关存储在会话变量中。我在用户登录时启动会话,但我只存储用户名(字符串)。这个问题会导致(add_to_cart()方法中的错误吗?
could this error be related how the data is stored in the session variable. I start the session, when user logs in, but I am only storing username(string). Could this issue be causing the error in the (add_to_cart() method?
protected void ValidateUser(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["#######"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
con.Close();
Session["UserAuthentication"] = Login1.UserName;
Response.Redirect("~/Default.aspx");
// FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
}
请进一步咨询。
谢谢。
Please advice further.
Thank you.
推荐答案
您将使用此代码代替那个代码,
You would be using this code instead of that one,
List<string> cart = new List<string>();
// Add it to the list
cart.Add(Convert.ToString(Session["UserAuthentication"]));
</string></string>
通过这种方式,您可以将新元素添加到您拥有的通用列表中。您不能将字符串转换为List< string>。
This way you can add a new element to the generic list you're having. You donot convert a string to a List<string>.
这篇关于如何在会话变量中存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!