![](/img/trans.png)
[英]C# ASP.NET MVC Manually Accessing Request.Form & Potentially Dangerous values
[英]Request.Form is empty (asp.net c#)
我一直在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
始終為null。 是否被(!IsPostBack)
包圍。 提交控件是Button
, LinkButton
還是Hyperlink
。 Request.Form["hdn"]
也為null。 我已重新啟動計算機,以防萬一,但仍然不高興。 我想必會遺漏一些非常簡單的東西,但看不到
這是首頁,后面的代碼一無所有
<%@ 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;
}
}
}
在confirm.aspx
使用PreviousPage.FindControl
代替:
HiddenField hdnFieldName = this.PreviousPage.FindControl("hdnConfirm") as HiddenField;
string hiddenValue = string.Empty;
if (hdnFieldName != null)
{
hiddenValue = hdnFieldName.Value;
}
這是一個很好的例子,可以幫助您入門。
這里發生了什么:
在VS 2013和Asp.Net v4.5.1中,默認情況下啟用了FriendlyUrls
功能。
該FriendlyUrls功能不種Asp.Net的路由,從而改變從URL中localhost/webform1.aspx
到localhost/webfrom1
PostbackUrl
屬性不能與Asp.Net路由結合使用。 使用ASP.NET路由時, PreviousPage
URL是最終的路由URL。 運行時將檢查由路由URL現在所代表的文件,這將是webform1
和不webfrom1.aspx
。 由於沒有webform1
這樣的文件,因此它將始終將PreviousPage
設置為null
。
可能的解決方案:
因此,現在您知道手頭的問題。
1.)在這種情況下,請不要使用Asp.Net Friendly Urls的路由系統,因此,請嘗試將<%@ PreviousPageType VirtualPath="~/WebForm1.aspx"%>
到webform2.aspx
頁面並進行檢查。
2)或,如果您保留FriendlyURLs並因此保留路由系統,請在代碼中進行更改以使用其他替代方法讀取Form值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.