I am having trouble binding a model that contains list of objects. There are no problems when i try to pass the data from the controller to the view, but when i want to send the data back, i get a message that the method doesnt exists.
I am using an ajax call and as data i put $form.serialize() and can see the list with all the data in fiddler, but i am having no luck with the binding.
The Model is:
public class Single
{
public int Id {get;set;}
public string Name {get;set;}
public List<SimpleDropdown> dddl {get;set;}
public int SelectedEmp {get;set;}
}
public class MainModel
{
public List<Single> main_model_list {get;set;}
}
In my controller the method for now is:
[HttpPost]
public string SaveModel(MainModel model)
{
return "";
}
This method doesn't get called, but when i remove the parameter the calling works. So i'm sure that the binding doesn't work. I had a lot more complex model, but i simplified it as much as i can and still couldn't get it to work.
So my question is how can i test this to see what is the problem?
Edit:
I dont have the code at the moment, but that code is functional because i use it in other places in the project. It is something like this:
$("#form").submit(function( ) {
$.ajax({
url: "/Controller/SaveModel",
type: "POST",
data: $(this).serialize()
});
});
The form looks something like this:
@using (Html.BeginForm("SaveModel", "Home", FormMethod.Post, new { id = "form" }))
{
@for (var z = 0; z < ViewBag.groupes.Length; z++)
{
<div style="border-left: 1px solid black">
<h1>@ViewBag.groupes[z]</h1>
</div>
}
@for (var i = 0; i < Model.main_model_list.Count; i++)
{
<div>@Html.LabelFor(x => x.main_model_list[i].Id)</div>
<div>@Html.LabelFor(x => x.main_model_list[i].Name)</div>
<div style="float: left">@Html.DropDownListFor(x => main_model_list[i].SelectedEmp, new SelectList(main_model_list[i].dddl, "Id", "Value", main_model_list[i].SelectedEmp), new { @class = "preferences_dd_lists" })</div>
}
}
In the MVC pattern, Model binding maps the HTTP request data to the parameters of a Controllers action method. The parameter can be of a simple type like integers, strings, double etc. or they may be complex types. MVC then binds the request data to the action parameter by using the parameter name.
So the two-way data binding means we can perform both read and write operations. In our previous article Data Binding in Spring MVC with Example, we have discussed how to write-to-variable task and in this article, we mainly focus on the read-from-a-variable task.
You can change your code.
data:{ model:$(this).serialize()}
Because you don't give the parameter name, the mvc model binding do not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With