繁体   English   中英

在asp.net中使用会话时出现错误

[英]I am getting error while using sessions in asp.net

我有2个表UsersHobbies userId is primary key in Users table and it is foreign key in is primary key in table and it is foreign key in Hobbies table. I want same table and it is foreign key in table. I want same table. I want same in both tables. When user logged in he gets table. I want same userId in both tables. When user logged in he gets in both tables. When user logged in he gets userId . On next page there is hobbies page where user have to fill info and the same . On next page there is hobbies page where user have to fill info and the same应该. On next page there is hobbies page where user have to fill info and the same userId`保存到“兴趣爱好”表中。 我为此使用会话,但它给异常

"Error converting datatype object to int."

我的代码是:

这是用户页面上的代码

protected void loginbtn_Click(object sender, EventArgs e)
{
    SqlCommand cmd1 = new SqlCommand("select UserId from Users where username=@username and password=@password",con);
    Session["ID"] = cmd1;
}

这是关于爱好的代码:

protected void Button4_Click(object sender, EventArgs e)
{
    int id= Convert.ToInt32(Session["ID"]);
    cmd.Parameters.AddWithValue("@UserId",id);
    con.Open();
    cmd.ExecuteNonQuery();
}

我是会话和存储过程的新手。 这是我的第一个Web应用程序。 请帮助我改善。

您不应将command存储在会话中,而应将其转换为integer

loginbtn_Click

protected void loginbtn_Click(object sender, EventArgs e)
{
    string conString = "xxxxxxxxxxxxxxxxxxxxxxxx";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (var cmd = new SqlCommand(
        "select UserId from Users where username=@username and password=@password",
        con))
        {
            cmd.Parameters.AddWithValue("@username", username.Text);
            cmd.Parameters.AddWithValue("@password", password.Text);
            var id = cmd.ExecuteScalar();
            Session["ID"] = id;

        }
    }
}

Button4_Click

protected void Button4_Click(object sender, EventArgs e)
{
    string conString ="xxxxxxxxxxxxxxxxxxxxxxxxxx";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (var cmd = new SqlCommand("select * from Users where UserId=@UserId",con))
        {
            var id= Convert.ToInt32(Session["ID"]);
            cmd.Parameters.AddWithValue("@UserId",id);
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                //get the data
            }       
        }
    }
}

您需要首先执行SQLCommand以获得UserID的值。 现在,您正在传递一个SQLCommand对象,该对象显然不是整数值。 要解决该错误,您需要执行以下操作:

using (SqlConnection con = new SqlConnection (connectionstring))
{
 SqlCommand cmd1 = new SqlCommand("select UserId from Users where username=@username and password=@password",con);
 cmd.Parameters.AddWithValue("@username", username.Text);
 cmd.Parameters.AddWithValue("@password", password.Text);
 con.Open();
 int UID = (int)cmd1.ExecuteScalar(); //Execute command and assign value
 Session["ID"] = UID; //Now set session variable
}

当然,您需要处理异常等等,但这应该可以帮助您入门。

首先,我想通知您,您将command对象存储在Session而不是UserID 所以你得到这个错误!

Users.aspx页上:

在会话中存储UserID:

 using (SqlConnection con = new SqlConnection (yourConnectionString))
    {
     SqlCommand mycmd = new SqlCommand("select UserId from Users where  username=@username and password=@password",con);
    //add parameters to pass the username & password here
      mycmd.Parameters.AddWithValue("@username", username.Text);
      mycmd.Parameters.AddWithValue("@password", password.Text);
     if (con.State != ConnectionState.Open)
      {
           con.Close();
           con.Open();
      }

     int userID = (int)mycmd.ExecuteScalar();
     Session["UserID"] = userID; //Store USerID in session
     con.Close();
    }

我不简单使用的原因:

if (con.State == ConnectionState.Closed)
{
    con.Open();
}

是因为ConnectionState也可以是:

Broken, Connnecting, Executing, Fetching

此外,Microsoft声明关闭并重新打开连接“将刷新State的值”。 更多细节

Hobbies.aspx页面上:

使用会话用户ID:

if(Session["UserID"]!=null)
{
int userID=Convert.ToInt32(Session["UserID"])
//do other stuff
}

插入兴趣表:

private void btnInsertHobbies_Click(object sender, EventArgs e)
    {
        int userID=0;
        if(Session["UserID"]!=null)
        {
          userID=Convert.ToInt32(Session["UserID"]);
        }

        //add Here fields of hobbies table
        string hobby1= textBox2.Text;
        string hobby2= textBox3.Text;
        if (conn2.State != ConnectionState.Open)
        {
           conn2.Close();
           conn2.Open();
        }

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn2;
        cmd.CommandText = "INSERT INTO Hobbies(userID, hobby1, hobby2)   VALUES(@userID,@hobby1,@hobby2)";

        cmd.Parameters.AddWithValue("@userID", userID);
        cmd.Parameters.AddWithValue("@hobby1", hobby1);
        cmd.Parameters.AddWithValue("@hobby2", hobby2);

        cmd.ExecuteNonQuery(); 

        conn2.Close();
    }

注意:请根据您的表格字段进行更改,如果有帮助,请标记为答案!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM