2009-12-24 21 views
2

我使用下面的紙條將數據發佈到ASP.Net如何獲取表單值在ASP.Net使用Jquery.post

$.post(window.location, { name: "John", time: "2pm" }) 

在我的Page_Load事件時,我檢查Request.Forms.AllKeys但伯爵的數字爲零。

我的形式是 <form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm">

回答

2

$.post是AJAX調用的jQuery。它與您的form上的post無關。

可以使用PageMethod實現你想什麼:

創建您的代碼隱藏像

[WebMethod] 
public static void HandleMyPost(string name, string time) 
{ 
    //do something 

} 

然後,ScriptManager控件添加到您的.aspx頁面中,並設置EnablePageMethods="true"

然後從JavaScript(在您$.post現在是)通過

PageMethods.HandleMyPost(function() {}, "John", "2pm") 
+2

沒有人應該使用像「PageMethods」這樣的ASP.NET特定技術來生成一個簡單的AJAX帖子。 – 2009-12-24 14:46:39

+0

他現在正在對他的當前頁面做一個新的頁面請求,並且進行一個全新的頁面循環,這比僅使用PageMethod更糟。 PageMethods只是在ASP.Net中創建AJAX調用的最簡單方法,您可以使用'pagename.aspx/handlemypost /'調用頁面來使用真正的'jQuery.post';所以你不必堅持ASP.Net AJAX。這只是最容易實現,方便的解決方案。 – 2009-12-24 20:27:56

+0

@Jan - 你說的沒錯。我有點錯過了那裏的樹林。 – 2009-12-24 23:07:06

1

打電話給你的方法代碼應工作。這是我做測試

在我後面的代碼我有:

protected void Page_Load(object sender, EventArgs e) 
{ 
    foreach (var key in Request.Form.AllKeys) 
    { 
     // do stuff here. 
    } 
} 

在頁面我有:

<script type="text/javascript"> 
    $(document).ready(function() 
    { 
     $('#btn').click(function() 
     { 
      $.post(window.location, { name: "John", time: "2pm" }); 
      return false; 
     }); 
    }); 
</script> 


<input type="button" id="btn" value="Click Me" /> 

screenshot http://imagebin.antiyes.com/images/0565978001261663525_33.jpg

當我按一下按鈕,有一個在foreach上的斷點我可以看到帖子的值,有兩個。

+0

@John,您使用的是哪個版本的jQuery? – 2009-12-24 15:24:07

+0

v1.3.2是我使用的版本。 – 2009-12-24 17:01:39

+0

奇怪 - 我認爲我們不同的結果可能是由於jQuery的多個版本。當我使用'窗口。位置'這對我來說在IE 6.0和Firefox 3.5.6使用jQuery 1.3.2失敗了。當我改變爲'location.href'(或'location.pathname')它工作正常。你使用什麼瀏覽器? – 2009-12-24 17:43:01

0

對於jQuery.postwindow.location對象不是有效的[url]參數。您應該使用window.location.href代替:

// or the shorter location.href 
$.post(location.href, { name: "John", time: "2pm" }) 

然而,不是失敗,jQuery的1.3.2(至少)回落到其默認ajaxSettings,這是(除其他事項外):

ajaxSettings: { 
    url: location.href, 
    type: "GET" 
} 

由於它發出一個GET請求,你顯然不會在Request.Form集合中看到你的數據。