这应该是一个错误 - ASP.NET Request参数

时间:2011-11-09 21:01:31

标签: asp.net textbox request postback

我在微软网站上发布了一些错误,虽然它们是真正的错误,但MSFT会将其作为设计关闭[而且我认为大多数人都喜欢MSFT]。这是一个我相信他们会因为设计而分类但对我来说这是一个严重的错误。

这就是我在ASPX页面(NET 3.5)中的全部内容。

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>        
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /><br />

<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>

代码隐藏

protected void Page_Load(object sender, EventArgs e)
    {  /* this works  */
        if (IsPostBack)
        {
            string txt = string.Empty;

            txt = Request.Params["TextBox1"];

            lblOutput.Text = "You entered : " + txt;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    { /* this does not */
            string txt = string.Empty;

            txt = Request.Params["TextBox1"];

            lblOutput.Text = "You entered : " + txt;

    }

现在,如果您包含另一个简单的HTML文本框(非ASP),就像这样

<input type="text" id="mytextbox" name="mytextbox" /> // still it below the existing one
txt = Request.Params["mytextbox"]; // change to this line instead of TextBox1

然后它在两个地方都有效。

3 个答案:

答案 0 :(得分:0)

protected void Button1_Click(object sender, EventArgs e)
{ /* Now this works which is weird but it does */
   If(IsPostback)
    {
        string txt = string.Empty;

        txt = Request.Params["TextBox1"];

        lblOutput.Text = "You entered : " + txt;
   }
}

因此,我应该结束这个问题。

答案 1 :(得分:0)

这是你在这个例子中所做的非常基本的事情,所以我非常怀疑这是一个错误。从这个例子来看,看起来你正在反对这个问题:

<强>标记

<asp:PlaceHolder ID="PlaceHolder1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server" />
    <asp:TextBox ID="TextBox2" runat="server" />
    <asp:TextBox ID="TextBox3" runat="server" />
    <asp:TextBox ID="TextBox4" runat="server" />
    ...
</asp:PlaceHolder>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /><br />  
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label> 

<强>代码隐藏

protected void Button1_Click(object sender, EventArgs e)
{
    foreach (TextBox txtCtrl in PlaceHolder1.Controls.OfType<TextBox>())
    {
        //append the textbox value to the label
        lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    List<TextBox> txtList = PlaceHolder1.Controls.OfType<TextBox>().ToList();

    for (int ctrlIndex = 0; ctrlIndex < txtList.Count; ctrlIndex++)
    {
        TextBox txtCtrl = txtList.ElementAt(ctrlIndex);
        if (txtCtrl != null)
        {
            lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
        }
    }
}

答案 2 :(得分:0)

如果您被迫使用Request对象而不是普通的asp:*控件,请按照以下方式使用它:

txt = Request["TextBox1"];

它会检查所有HttpRequest个收藏品。

  

QueryString,Form,Cookies或ServerVariables集合成员   在key参数中指定。如果找不到指定的密钥,   然后返回null。

相关问题