![](/img/trans.png)
[英]How to Post asp:FormView in ASP.NET WebForms by ajax of Jquery with model binding?
[英]ASP.Net Model binding - WebForms
我被要求在 ASP.Net WebForms 項目上工作,我想像在 ASP.Net MVC 中一樣使用 ModelBinding。
我在讓它工作時遇到了一些問題,如果可能的話,我希望得到一些幫助。
如果我想將模型綁定到 Form 上的對象,我需要在 FormView、GridView 等中執行此操作,但在這種情況下我想使用 FormView。
下面的代碼是我正在使用的簡化版本,但每一點都相關。
<asp:FormView runat="server" ID="frmMain" ItemType="WebFormsModelBinding.TestModel" SelectMethod="TestBinding_select" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txtName" Text="<%#: BindItem.Name %>" />
<br/>
<asp:TextBox runat="server" id="txtAge" Text=" <%#: BindItem.Age %>" />
</ItemTemplate>
</asp:FormView>
<asp:Button runat="server" id="bttnInsert" Text="button"/>
我有一個 JQuery 腳本試圖將數據傳回模型,但我不斷收到內部 500 錯誤
$(document).ready(function() {
$("#MainContent_bttnInsert")
.click(function() {
var params = {
Name: "Dave",
Age: 55
}
$.ajax({
type: "POST",
url: "default.aspx/TestBinding",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
//success: function (data) {
success: function () {
alert("it worked");
return false;
},
error: function (data) {
console.log(data);
alert("didnt work");
}
});
return false;
});
})
這應該在默認頁面中點擊此代碼
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static bool TestBinding(TestModel model)
{
return true;
}
public TestModel TestBinding_select()
{
var model = new TestModel
{
Name = "Simon",
Age = 33
};
return model;
}
}
public class TestModel
{
public string Name { get; set; }
public int Age { get; set; }
}
我遇到的問題是,因為我不能使用 ActionResult,所以我必須聲明一個不同的對象類型作為返回類型。 對於這個例子,我選擇了一個 bool 並且沒有具體的原因。
為了命中 WebMethod,我必須使方法靜態。
我得到的錯誤是
“無效的 Web 服務調用,缺少參數值:'model'。”
因此,在此實例中,我可以將模型傳遞給 UI 並將其呈現在 FormView 中,但我無法通過 JQuery 或回發將模型傳回。
有什么我遺漏的嗎,或者我真的必須將每個變量傳回,然后將值傳遞給類,從而使模型綁定在 WebForms 中幾乎毫無意義
如果您打算使用WebForms
,您應該習慣於使用PostBack
模型,否則您將不斷地與選定的框架作斗爭。
但是對於手頭的問題,請嘗試以下操作:
data: JSON.stringify({'model':params})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.