从查询字符串设置Viewstate

时间:2014-03-05 22:13:34

标签: asp.net c#-3.0

如果我在没有查询字符串的情况下加载此页面,那么!IsPostBack会正确设置viewstate变量,并且它可用于我的按钮单击事件。但是,如果我将M设置为某些内容并尝试在关闭Page_load事件之前自动启动按钮,则veiwstate变量为null并引发错误。任何想法如何解决这个问题?我能以某种方式直接将Viewstate对象传递给button1_Click事件吗?是否存在页面加载后的事件,如果存在查询字符串,我可以点击以发送我的按钮单击?

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["S"]))
        {
            TextBox1.Text = Request.QueryString["S"];

            if (string.IsNullOrEmpty(Request.QueryString["T"]) && string.IsNullOrEmpty(Request.QueryString["M"]))
            {
                Button1_Click(null, null);
            }

        }
        if (!string.IsNullOrEmpty(Request.QueryString["T"]))
        {
            TextBox2.Text = Request.QueryString["T"];
            Button1_Click(null, null);
        }
        if (!string.IsNullOrEmpty(Request.QueryString["M"]))
        {
            ViewState["checkedOEM"] = Request.QueryString["M"];
            Button1_Click(null, null);
        }
        if (ViewState["checkedOEM"] == null)
        {
            CheckBox1.Checked = true;
            checkedOEM = CheckBox1.Text;
            ViewState["checkedOEM"] = checkedOEM;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

所以我将Page_Load事件分解为事先和事后事件,以获得我正在寻找的行为。

    protected void Page_Init(object sender, EventArgs e) 
{
    if (!string.IsNullOrEmpty(Request.QueryString["M"]))
    {
        ViewState["checkedOEM"] = Request.QueryString["M"];            
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    //hide all fields untill they need to be shown
    HyperLink2.Visible = false;
    HyperLink3.Visible = false;
    Image1.Visible = false;
    debugLabel.Text = null;
    debugLabel2.Text = null;

    if (!IsPostBack)
    {
        LinkButton1.Visible = false;

        if (ViewState["checkedOEM"] == null)
        {
            CheckBox1.Checked = true;
            checkedOEM = CheckBox1.Text;
            ViewState["checkedOEM"] = checkedOEM;
        }
        if (!string.IsNullOrEmpty(Request.QueryString["M"]))
        {
            CheckBox1.Visible = false;
            CheckBox2.Visible = false;
            CheckBox3.Visible = false;
            CheckBox4.Visible = false;
            Button1.Visible = false;
        }
    }
    lblStatus.Text = string.Empty;
}

protected void Page_PreRender(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["S"]))
    {
        TextBox1.Text = Request.QueryString["S"];

        if (string.IsNullOrEmpty(Request.QueryString["T"]) && string.IsNullOrEmpty(Request.QueryString["M"]))
        {
            Button1_Click(null, null);
        }

    }
    if (!string.IsNullOrEmpty(Request.QueryString["T"]))
    {
        TextBox2.Text = Request.QueryString["T"];
        Button1_Click(null, null);
    }
    if (!string.IsNullOrEmpty(Request.QueryString["M"]))
    {            
        Button1_Click(null, null);
    }
}