Why is my Asp.Net Form arriving empty when I post

2019-02-25 13:25发布

I have the following HTML Code

<%@ Page Language="C#" %>

<html>
    <head>
        <title></title>
    </head>
    <body>
        <form id="frmSystem" method="post" action="target.aspx">
            <input id="txtTextField" type="text" />
            <input id="btnPost" value="Submit" onclick="javascript:frmSystem.submit();" type="button" />
        </form>
    </body>
</html>

The target Page is coming up but the form that it is receiving is empty. I have a break point on my target.aspx page and while I can see a form, it's keys are empty and Request["txtTextField"] gives me nothing.

Any clue why?

4条回答
ゆ 、 Hurt°
2楼-- · 2019-02-25 14:00

If you are using ASP.NET MVC, the input names need to be set with the "name" attribute rather than "id".

查看更多
Emotional °昔
3楼-- · 2019-02-25 14:07

You probably reset the form value in event handlers (such as page_load).

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-25 14:17

If you are using ASP.NET 4.5 like me, use below hints

  • Disable auto Friendly URLs in a Web Form project
    • settings.AutoRedirectMode = RedirectMode.Off; // in RouteConfig.cs
  • if you can:
    • remove action="CILandingPage.aspx" from form element
    • put a asp:button instead of normal button
    • set PostBackUrl="~/CILandingPage.aspx" on your asp:button

more resources with more detail that was useful to me

查看更多
小情绪 Triste *
5楼-- · 2019-02-25 14:21

Another option is to capture your Request.Form[] data in Application_BeginRequest on the Global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    //capture form data and preserve in query string
    if (Request.Form["txtTextField"]!= null)
    {
        Response.Redirect(Request.RawUrl + "?txtTextField=" 
          + Request.Form["txtTextField"]);
    }
    //or preserve in Session variable
    if(Request.Form["txtTextField"]!=null)
    {
        Session["txtTextField"]=Request.Form["txtTextField"];
    }
}

The problem is that the form data is lost on the automatic redirect which is applied by friendlyUrls - if you store that data as something other than form data, it is unnecessary to turn off friendlyUrls or set AutoRedirectMode to RedirectMode.Off.

查看更多
登录 后发表回答