类和全局变量中的存储过程

时间:2014-08-06 00:49:00

标签: c# asp.net sql-server class stored-procedures

我有一个名为UserInfo的类。在这个类中,我调用SQL存储过程来验证用户。存储过程返回输出。

我获取输出并将其存储在类中的局部变量中,在本例中只能在UserInfo类中访问。

这是班级:

public class UserInfo
{
    public void validateUser(string username, string password)
    {
        string constring = "Data Source=db;Initial Catalog=Portal;User ID=u;Password=p";

        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("agentAuthentication", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                cmd.Parameters.Add("@loginresults", SqlDbType.BigInt, 8);
                cmd.Parameters["@loginresults"].Direction = ParameterDirection.Output;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                int result =Convert.ToInt32(cmd.Parameters["@loginresults"].Value);

            }
        }
    }
}

在点击登录页面的按钮上,我调用此类来验证用户。

 protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            string username = text1.Value.Trim();
            string password = text2.Value.Trim();

            UserInfo u = new UserInfo();
            u.validateUser(username, password);

            int result = 0;

            if (result == 0)
            {
                Response.Write("<script>alert('Incorrect username or password');</script>");
            }

            if (result == 2)
            {
                Response.Write("<script>alert('Your account is inactive');</script>");
            }

            if (result != 0 && result != 2)
            {
                Session["isLoggedIn"] = 1;
                Response.Redirect("~/default.aspx");
            }

        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }

如何从存储过程中存储返回的值,以便我可以在按钮单击后面的代码中访问它?

如您所见,结果在两个地方声明。我想在类中声明结果并检查按钮单击事件的值。

存储过程返回三种类型的输出:

  1. 如果用户名或密码不正确,则返回0
  2. 如果帐户处于非活动状态,则返回2
  3. 否则返回用户的ID。

1 个答案:

答案 0 :(得分:2)

UserInfo班级更改public void validateUser(string username, string password)public int validateUser(string username, string password)并返回结果。在using子句之外声明此结果变量,并将其初始值设置为0。

btnLogin_Click更改u.validateUser(username, password);int result = u.validateUser(username, password);,您就完成了。