Asp.net
在 ASP.NET 中使用嵌入式標準 HTML 表單
我有一個標準的 aspx 頁面,我需要在其中添加另一個標準 HTML 表單並將其送出到另一個位置(外部站點),但是每當我按下送出按鈕時,該頁面似乎會回發而不是使用子表單操作網址。
下面是表單關係的模型。請注意,在實際部署中,表單將成為母版頁佈局的內容區域的一部分,因此表單需要獨立於母版頁表單送出。
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <form id="subscribe_form" method="post" action="https://someothersite.com" name="em_subscribe_form" > <input type="text" id="field1" name="field1" /> <input id="submitsubform" type="submit" value="Submit" /> </form> </div> </form> </body> </html>
這是一個有趣的問題。理想情況下,您只需要其他使用者提到的頁面上的 1 個表單標籤。您可能可以通過 javascript 發布數據而無需 2 個表單標籤。
範例取自此處,根據您的需要進行修改。不是 100% 確定這是否對您有用,但我認為這就是您必須採用的方法。
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> function postdata() { var fieldValue = document.getElementById("field1").value; postwith("http://someothersite.com",{field1:fieldValue}); } function postwith (to,p) { var myForm = document.createElement("form"); myForm.method="post" ; myForm.action = to ; for (var k in p) { var myInput = document.createElement("input") ; myInput.setAttribute("name", k) ; myInput.setAttribute("value", p[k]); myForm.appendChild(myInput) ; } document.body.appendChild(myForm) ; myForm.submit() ; document.body.removeChild(myForm) ; } </script> </head> <body> <form id="form1" runat="server"> <div> <div> <input type="text" id="field1" name="field1" /> <asp:Button ID="btnSubmitSubscribe" runat="server" Text="Submit" OnClientClick="postdata(); return false;" /> </div> </div> </form> </body> </html>如果 javascript 不是一個可行的選項 - 您可以使用 .Net 的 HttpWebRequest 對像在後面的程式碼中創建 post 呼叫。在後面的程式碼中看起來像這樣(假設您的文本欄位是一個 asp 文本框:
private void OnSubscribeClick(object sender, System.EventArgs e) { string field1 = Field1.Text; ASCIIEncoding encoding=new ASCIIEncoding(); string postData="field1="+field1 ; byte[] data = encoding.GetBytes(postData); // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://someotherwebsite/"); myRequest.Method = "POST"; myRequest.ContentType="application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream=myRequest.GetRequestStream(); // Send the data. newStream.Write(data,0,data.Length); newStream.Close(); }