使用表单传递参数,request处理参数出现"未将对象引用设置到对象的实例

跟着于海淘的教程看了一下asp.net 教程,做着发现一个实例老是调不对,一下是:  
  学做了个登陆验证  
  是这样的   :  
  当从数据库验证用户名密码正确后  
  用POST方法把两个控件提交给另一个页面  
  <form   id="Form1"   method="post"   action="main.aspx"   runat="server">  
   
  然后在main.aspx里面的Page_Load接收  
  string   userName   =   Request.Form.Get("txtUserName").ToString();  
  string   userPwd     =   Request.Form["txtPwd"].ToString();  
   
  怪事出现了  
  运行时.我无法如料想地进入main.aspx页面  
  而是:  
  //以下为错误页面的内容  
   
  “/WebTest”应用程序中的服务器错误。  
   
  说明:   执行当前   Web   请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。    
   
  异常详细信息:   System.NullReferenceException:   未将对象引用设置到对象的实例。   
   
原因是因为你的login.htm 文件里的表单form 里的参数你写错了

我也遇到过这样的情况,request 接受的是textbox  name 的值,不是id,切记!

贴一下代码吧

login.htm 的代码

<form method="post"action="Response.aspx">

 <td style="width: 201px; height: 57px">
                <input id="txtUserName1" style="z-index: 100; left: 113px; position: absolute; top: 20px"
                    type="text" name="txtUserName" />
            </td>

 <td style="width: 201px; height: 52px">
                <input id="txtUserPwd1" style="z-index: 101; left: 115px; position: absolute; top: 84px"
                    type="text" name="txtUserPwd" />
            </td>

 <td style="width: 201px; height: 61px">
                &nbsp;
                <input id="btnlogin1" style="z-index: 103; left: 149px; width: 53px; position: absolute;
                    top: 134px" type="submit" value="提交" />
            </td>

接受页面的处理方法 Response.aspx.cs文件

 string userName, userPwd;
        if (Request.Form["txtUserPwd"] != null)
        {
            userName = Request.Form["txtUserPwd"].ToString();
            userPwd = Request.Form["txtUserPwd"].ToString();
            Response.Write("登陆的用户名为" + userName + ";用户密码为"+userPwd);
        }
        else
        {
            userName = "";
            userPwd = "";
        }

当然这里你可以更简单,随便了^

posted on 2008-07-28 11:35  9who  阅读(1753)  评论(0编辑  收藏  举报

导航