[英]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.