Request.Form为空(asp.net c#)

时间:2015-08-20 08:52:24

标签: c# asp.net

我在ASP.Net c#中做了一些非常聪明的事情(我认为),以至于简单的东西更难(如果有意义的话)

我的页面中有这段代码

<form id="form1" runat="server">
    <asp:HiddenField runat="server" ID="hdnConfirm" value="Hello World" />
    <asp:LinkButton runat="server" PostBackUrl="/confirm.aspx" Text="Confirm">
    </asp:LinkButton>
</form>

我在confirm.aspx中有这段代码。

if !(IsPostback)
{
    lblConfirm.Text = Request.Form["hdnConfirm"]
}

我期待这很简单但是当我点击按钮并转到页面“confirm.aspx”时,Request.Form没有值。我错过了什么?

[测试]

我在VS2013中对一个全新的Web表单项目进行了测试。 Dot.Net 4.5.1这不起作用。 PreviouPage始终为空。是否被(!IsPostBack)包围。提交控件是ButtonLinkButton还是Hyperlink无关紧要。 Request.Form["hdn"]也为空。我已经重新启动了我的电脑以防万一,仍然没有快乐。我错过了一些非常简单的东西,我确信它但是我看不出是什么

这是

背后代码中的第一页
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:LinkButton runat="server" PostBackUrl="~/WebForm2.aspx">click</asp:LinkButton>
        <asp:HiddenField runat="server" ID="hdn" Value="3" />
    </div>
    </form>
</body>
</html>

这是第二页

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication2.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

背后的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string s = ((HiddenField)this.PreviousPage.FindControl("hdn")).Value;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

confirm.aspx上使用PreviousPage.FindControl代替:

HiddenField hdnFieldName = this.PreviousPage.FindControl("hdnConfirm") as HiddenField;
string hiddenValue = string.Empty;
if (hdnFieldName != null)
{
    hiddenValue = hdnFieldName.Value;
}

flush time是让你入门的好榜样。

答案 1 :(得分:0)

发生了什么事情:

默认情况下,VS 2013和Asp.Net v4.5.1中启用了一项功能FriendlyUrls

FriendlyUrls功能执行Asp.Net路由,从而将网址从localhost/webform1.aspx更改为localhost/webfrom1

PostbackUrl属性不能与Asp.Net Routing结合使用。使用ASP.NET路由时,PreviousPage URL是最终路由的URL。运行时将立即检查路由URL表示的文件,该文件将为webform1而不是webfrom1.aspx。由于没有webform1这样的文件,因此它始终会将PreviousPage设置为null

可能的解决方案:

所以,现在你知道了手头的问题。

1。)在这种情况下,要么不使用Asp.Net Friendly Urls的路由系统,请尝试将<%@ PreviousPageType VirtualPath="~/WebForm1.aspx"%>添加到webform2.aspx页面并进行检查。

2。)或者,如果您保留FriendlyURL并因此保留Routing系统,请在代码中进行更改以使用其他替代方法读取Form值。