简体   繁体   English

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

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

I have 2 tables Users and Hobbies . 我有2个表UsersHobbies userId is primary key in Users table and it is foreign key in Hobbies table. I want same 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 userId in both tables. When user logged in he gets 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 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 userId` should get saved into Hobbies table. . 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`保存到“兴趣爱好”表中。 I am using session for this, but it is giving exception as 我为此使用会话,但它给异常

"Error converting datatype object to int."

My code is: 我的代码是:

this is a code on Users Page 这是用户页面上的代码

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;
}

and this is the code on hobbies: 这是关于爱好的代码:

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

I am new to sessions and stored procedure. 我是会话和存储过程的新手。 This is my first web app. 这是我的第一个Web应用程序。 Please help me to improve. 请帮助我改善。

You shouldn't store a command in a session let along convert it to a integer . 您不应将command存储在会话中,而应将其转换为integer

loginbtn_Click 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 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
            }       
        }
    }
}

You need to execute the SQLCommand first to get the value of your UserID . 您需要首先执行SQLCommand以获得UserID的值。 Right now, you are passing an SQLCommand object, which obviously isn't an integer value. 现在,您正在传递一个SQLCommand对象,该对象显然不是整数值。 To fix the error, you would need to do something like this: 要解决该错误,您需要执行以下操作:

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
}

Of course, you need to handle exceptions and so on, but this should get you started. 当然,您需要处理异常等等,但这应该可以帮助您入门。

First i want to notify you that you are storing the command object into the Session and not the UserID . 首先,我想通知您,您将command对象存储在Session而不是UserID so you are getting this error! 所以你得到这个错误!

On Users.aspx Page: Users.aspx页上:

Storing UserID in session: 在会话中存储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();
    }

The reason I'm not simply using: 我不简单使用的原因:

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

Is because the ConnectionState can also be: 是因为ConnectionState也可以是:

Broken, Connnecting, Executing, Fetching

Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." 此外,Microsoft声明关闭并重新打开连接“将刷新State的值”。 More Details 更多细节

On Hobbies.aspx Page: Hobbies.aspx页面上:

Using Session UserID: 使用会话用户ID:

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

Insert Into Hobbies table: 插入兴趣表:

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();
    }

NOTE: please make changes according to your table fields and mark as answer if it help you! 注意:请根据您的表格字段进行更改,如果有帮助,请标记为答案!

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

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