【问题标题】:Query String Value always 0查询字符串值始终为 0
【发布时间】:2013-04-20 04:36:54
【问题描述】:

这可能很简单,但我看不出有什么问题..

我将此字符串添加到我的网址:/projects.aspx?pid=3

在我后面的代码中,我试图像这样获取这个值:

public partial class Projects : System.Web.UI.Page
{
    public int pid { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            pid = Convert.ToInt32(Request.QueryString["pid"]); //this is returning 0 when it should have a value.
            DataBind(true);

            PopulateTestSuiteList();
        }

        TestSuitesDataList.ItemCommand += new RepeaterCommandEventHandler(this.Item_Command);
    }

当我尝试查看其他函数中的 pid 值时,它总是给我“0”。我不明白为什么它不能像它应该的那样给我 3?

以下是示例函数:

private void ExecuteInsert(string TestSuiteName, string TestSuiteDescription, int ProjectID)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "INSERT INTO TestSuites (ProjectID, TestSuiteName, TestSuiteDescription) VALUES " + " (@ProjectID,@TestSuiteName,@TestSuiteDescription)";
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);

            SqlParameter[] param = new SqlParameter[3];

            param[0] = new SqlParameter("@TestSuiteName", SqlDbType.NVarChar, 50);
            param[1] = new SqlParameter("@TestSuiteDescription", SqlDbType.NVarChar, 200);
            param[2] = new SqlParameter("@ProjectID", SqlDbType.Int);

            param[0].Value = TestSuiteName;
            param[1].Value = TestSuiteDescription;
            param[2].Value = pid;

            for (int i = 0; i < param.Length; i++)
            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

    protected void AddTestSuiteButton_Click(object sender, EventArgs e)
    {
        //checks whether the test suite name already exists in the database and stops duplicates from being added for the same project
        string checkExistsQuery = "SELECT TestSuiteName FROM TestSuites WHERE TestSuiteName = @TestSuiteName and @ProjectID = " + pid;

        SqlConnection conn = new SqlConnection(GetConnectionString());
        SqlCommand checkExistsCmd = new SqlCommand(checkExistsQuery, conn);

        SqlParameter c1 = new SqlParameter("TestSuiteName", TxtTestSuiteName.Text);
        SqlParameter c2 = new SqlParameter("ProjectID", pid);

        checkExistsCmd.Parameters.Add(c1);
        checkExistsCmd.Parameters.Add(c2);

        conn.Open();

        SqlDataReader rd = checkExistsCmd.ExecuteReader();

        if (rd.HasRows)
        {
            lblAddTestSuiteMessage.Text = "Oops, a Project with that name already exists.";
            rd.Close();
            conn.Close();
        }
        else
        {
            string FormattedTestSuiteDescription = TxtTestSuiteDescription.Text.Replace("\r\n", "<br />");
            //call the method to execute insert to the database
            ExecuteInsert(TxtTestSuiteName.Text, FormattedTestSuiteDescription, pid);

            lblAddTestSuiteMessage.Text = "Project has been added successfully";
            ClearControls(Page);
        }

        rd.Close();
        conn.Close();
        Response.Redirect(Request.RawUrl);
    }

在后面的相同代码中,这个函数似乎很乐意提取正确的数据并将其显示在我的页面上——它也在使用 PID 吗??

        private void PopulateTestSuiteList()
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        conn.Open();
        string sql = "SELECT TestSuiteID, ProjectID, TestSuiteName, TestSuiteDescription FROM TestSuites WHERE ProjectID = " + pid + "ORDER BY TestSuiteName ASC";
        SqlCommand cmd = new SqlCommand(sql, conn);

        SqlDataReader rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            TestSuitesDataList.DataSource = rd;
            TestSuitesDataList.DataBind();
        }
        conn.Close();
    }

【问题讨论】:

  • 取决于你所说的其他功能
  • 我添加了几个来帮助 :)
  • 嗯。 property 值会在 Page_Load 事件上重置吗?

标签: c# asp.net query-string


【解决方案1】:

这可能是由于没有完全理解page life cycle造成的。您在 Page_Load 上设置了 pid,但可能在页面尚未加载或重新加载时(例如回发后)在某处使用它。

如果您从查询字符串中获取pid 值并需要在回发时使用它,则需要将其存储在会话变量隐藏字段中这页纸。将其分配给页面类变量不会像您在这里所做的那样持久化。

【讨论】:

  • 啊,你是对的。我把 if (!Page.IsPostBack) 包裹在 pid = Convert.ToInt32(Request.QueryString["pid"]);并尝试再次添加,它起作用了!感谢您的帮助。
  • 请注意,这样做是允许用户在请求和回发之间更改 pid 的值。
【解决方案2】:

我会检查每个不方便的值,例如 null 或无效字符串,我的代码是:

if (Request.QueryString["pid"] != null)
{
    int pid;
    if (int.TryParse(Request.QueryString["pid"].ToString(), out pid))
    {
        //Then its OK and you have an 
        //integer, put the codes here
    }
    else
    { 
        //The query string has value
        //but the value is not valid
        //(not an integer value)
    }
}

【讨论】:

  • 您好,感谢您的回复。根本不是一个坏主意。我同意,我应该为此添加一些检查。我想我真正的问题是,即使是我的示例中的有效 pid(例如 3)当前也被插入到 pid 0
【解决方案3】:

由于您使用Convert.ToInt32作为

 Convert.ToInt32(Request.QueryString["pid"]);

如果它为空,Convert.ToInt32 函数将返回 0。

尝试使用Int32.Parse(Request.QueryString["pid"]) 看看天气是否会出现空值异常。

如果是,则您的 Query string 中的 pid 没有任何值。在查询字符串中检查您从哪里发送pid

更多

您也可以使用Session,因为值可能会在编辑或更新事件中丢失。所以你可以这样做

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       if(Request.QueryString["pid"]!=null && Session["pid"]!=null)
        pid = Convert.ToInt32(Request.QueryString["pid"]); 
        DataBind(true);
        PopulateTestSuiteList();
    }
    TestSuitesDataList.ItemCommand += new RepeaterCommandEventHandler(this.Item_Command);
}

在你的函数内部ExecuteInsert函数

private void ExecuteInsert(string TestSuiteName, string TestSuiteDescription)
{
     SqlParameter c2 = new SqlParameter("ProjectID", Int32.Parse(Session["pid"].ToString()));

【讨论】:

  • 您好,感谢您的回复。我不确定这一点 - 它正在将所有内容添加到项目 ID 0。如果我浏览到 ?pid=0 或 ?pid=1 等,它仍会显示数据库中正确 ID 的数据,但现在不插入如果有意义的话,更长的时间会进入正确的 projectID。所以这个函数仍在用正确的数据填充页面,它使用的是 pid 值..(添加到原始描述)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 2012-06-15
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多