【发布时间】:2017-01-27 10:16:28
【问题描述】:
我被要求处理一个 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 中几乎毫无意义
【问题讨论】:
标签: c# asp.net webforms model-binding