如何使用链接中的值?

时间:2019-09-29 18:18:44

标签: c# asp.net webforms

我不确定如何问这个问题,我试图寻找解决方案,但是由于不知道要搜索什么而没有运气。因此,我有了一个linkbutton来将用户定向到addtocart。带有产品ID和链接的aspx应该看起来像这样

addtocart.aspx/?id=1

我的问题是如何使用重定向用户的链接中的id值并将其保存到购物车的另一个​​数据库中。这是我当前的进度,但仍然无法显示ID(此代码在addtocart.aspx的页面加载下)

if (!IsPostBack)
{
    String contact_id = Id;
    int intTest = Convert.ToInt32(contact_id);

    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Product WHERE Id=" + intTest))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);

                    foreach (DataRow row in dt.Rows)
                    {
                        string id = row["Id"].ToString();
                        string Product_Name = row["Product_Name"].ToString();
                        string Product_Price = row["Product_Price"].ToString();
                        string username = Session["Username"].ToString();

                        con.Close();
                        con.Open();
                        string query = "INSERT INTO Cart (Guest_Id, Product_Name, Product_Price) values (@Guest_Id, @Product_Name, @Product_Price)";

                        SqlCommand cmd1 = new SqlCommand(query, con);

                        cmd1.Parameters.AddWithValue("@Username", username);
                        cmd1.Parameters.AddWithValue("@Product_Name", Product_Name);
                        cmd1.Parameters.AddWithValue("@Product_Price", Product_Price);

                        cmd1.ExecuteNonQuery();

                        Response.Redirect("Dining.aspx");

                        con.Close();
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

要获取查询字符串参数,只需使用Request.QueryString。所以,

// this gets the 'id' parameter from rthe query string, as a string
string contact_id = Request.QueryString["id"];