2011-12-19 29 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