ASP.Net模型绑定 – WebForms
我被要求在ASP.Net WebForms项目上工作,我想像在ASP.Net MVC中那样使用ModelBinding。
我在解决这个问题上遇到了一些问题,如果可能的话,我希望得到一些帮助。
如果我想将模型绑定到Form上的对象,我需要在FormView,GridView等中执行此操作,但在此实例中,我想使用FormView。
下面的代码是我正在使用的简化版本,但是每个位相关。
<asp:TextBox runat="server" ID="txtName" Text="" />
<asp:TextBox runat="server" id="txtAge" Text=" " />
我有一个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})