2011-12-19 28 views
0

我有一个C#aspx的形式,我需要输入它的数据到SQL数据库,然后返回一个响应说成功与否。我不知道如何获取从Default.aspx页面发送的表单数据。我的基本代码结构如下:C#ASPX - 表单提交查询

Default.aspx的

<form runat="server" name="aForm" action="Results.aspx" method="post" onsubmit="ValidateForm()"> 
    <input name="firstname" type="text" /> 
    <input name="surname" type="text" /> 
    <input type="submit" value="Submit" /> 
</form> 

Results.aspx.cs

public partial class AwardsForm : System.Web.UI.Page { 

    protected void Page_Load(object sender, EventArgs e) { 

    if (!this.IsPostBack){ 
     Response.Redirect("Default.aspx"); 
    } else (this.IsPostBack) { 
     writeResults(FormSubmit()); 
    } 

    protected boolean FormSubmit() { 
     // get form data and insert it into SQL 
     // return true/false based on success 
    } 

    protected void writeResults(boolean results) { 
     if (results == true) { 
     Response.Write ("Success"); 
     } else { 
     Response.Write ("Failed"); 
     } 
    } 

} 

回答

4

您可以通过Request.Form["key"]得到提交的表单数据,或者,如果你的表单元素用runat="server"装饰,那么你应该能够通过你的代码在后面的代码中抓住他们

<asp:TextBox id="yourTb" runat="server"></asp:TextBox> 

string postedText = yourTb.Text; 

或者你也可以这样做(虽然这是很少见)

<input type="text" runat="server" id="yourOtherTb" /> 

string otherPostedText = yourOtherTb.Value; 

或者,如果你与纯粹的HTML表单输入工作:

<input type="text" id="clientTb" name="clientTb" /> 

string clientText = Request.Form["clientTb"]; 
+0

非常感谢,看起来不错。有关这台机器关键业务的任何想法?这是本地表格,不会在网上使用。 我曾尝试不采取以下措施:http://sharemypoint.wordpress.com/2009/04/15/machinekey-in-webconfig/。 – 2011-12-19 22:36:17

+1

不知道机器的关键东西@Bonjour - 对不起 – 2011-12-20 00:07:21

+0

没问题,我用它在页面上使用了黑客工作。谢谢你的回复,非常感谢。 – 2011-12-20 01:11:31

1

您可以通过以下尝试码。

string firstname = Request.Form["firstname"] 

string surname = Request.Form["surname"] 
+0

谢谢队友,这个答案很好。如果您对我上面Adam的回答有任何意见,那将非常感谢。 – 2011-12-19 23:15:16

1

既然你正在做这样的

<input name="firstname" type="text" /> 
    <input name="surname" type="text" /> 
    <input type="submit" value="Submit" /> 

东西输入控件的属性name张贴回服务器(IIS)。因此,你会这样做。

If(IsPostBack) 
{ 
    string firstName = Request.Forms["firstname"]; 
    string surName = Request.Forms["surname"]; 

if(string.IsNullOrEmpty(firstName)) 
{ 
Response.Write("Firstname is required"); 
} 
} 
+0

谢谢队友,这个答案很好。如果您对我上面Adam的回答有任何意见,那将非常感谢。 – 2011-12-19 23:07:24

+1

@Bonjour http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx机器密钥用于在发布到同一域中的其他应用程序时加密和解密表单数据。您的要求不需要,请从web.config中删除''部分 – Deeptechtons 2011-12-20 04:08:03