问题
I have been asked to work on an ASP.Net WebForms project and I want to use ModelBinding like I do in ASP.Net MVC.
I am having some problems in getting this to work and would like some help if possible.
If I want to bind a model to objects on a Form I need to do this in a FormView, GridView and so on but in this instance I want to use a FormView.
The below code is a simplified version of what I am working with but everybit relevant.
<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"/>
I have a JQuery script that is attempting to pass the data back to the model but I keep getting a Internal 500 Error
$(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;
});
})
This should hit this code in the default page
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; }
}
The problems I am having is that as I cant use an ActionResult I have to declare a different object type as the return type. For this example I have chosen a bool and there is no specific reason for this.
In order to hit a WebMethod I have to make the method static.
The error that I am getting is
"Invalid web service call, missing value for parameter: 'model'."
So, I can pass a model to the UI and present it in the FormView in this instance, but I cannot pass a model back via JQuery or a postback.
Is there anything that I am missing, or do I really have to pass each variable back and then pass the values to the class thus making model binding almost pointless in WebForms
回答1:
If you ware going to work with WebForms
, you should get used to working with the PostBack
model, or you're going to be constanty fighting against the selected framework.
But for the question at hand, try the following:
data: JSON.stringify({'model':params})
来源:https://stackoverflow.com/questions/41891573/asp-net-model-binding-webforms