Reputation: 21661
This is my jquery function. I'd like to to post this object to the controller. Every thing works fine except the ListOfCBToDisplay, which is a list.
<script>
function Submit_Movie() {
//
var title = $('[id*="Title"]').val();
var yearOfMaking = $('[id*="YearOfMaking"]').val();
var description = $('[id*="Description"]').val();
var movie =
{
"Title": title,
"YearOfMaking": yearOfMaking,
"Description": description,
"ListOfCBToDisplay" : []
};
//
var $cbx = $('[id*="cbx"]');
$cbx.each(function () {
var id = GetID($(this).attr('id'));
var ck = $(this).prop("checked");
alert(id + ", " + ck); //The alert is displaying correctly all the values
var new_obj = { "ID": id, "Value": ck, "Text": "" };
movie.ListOfCBToDisplay.push(new_obj);
})
//
var url = "@Url.Action("AddEditMovie", "Admin")";
$.post(url, movie, function (data) {
location.reload();
});
}
function GetID(elt_id) {
var _id = elt_id.split('_');
if (_id.length == 2) {
return _id[1];
}
else {
return 0;
}
}
This is the Movie class
public class Movie
{
public Movie()
{
ListOfCBToDisplay = new List<CheckBoxToDisplay>();
}
// more properties ...
public List<CheckBoxToDisplay> ListOfCBToDisplay { get; set; }
}
And this is the action
[HttpPost]
public ActionResult AddEditMovie(Movie movie)
{
//More here ...
}
Any reason why all the primitive properties are getting their values while the objects in the list have null values, i.e. ID = 0, Text = null, and Value = false ? However, the number of objects is always correct, only the values are null.
Thanks for helping
Upvotes: 0
Views: 103
Reputation: 10423
You could try to use JSON to JSON.stringify(myObject);
the object. Or you can simply serialize your string with the JS join
method:
var myList = [];
$cbx.each(function () {
var id = GetID($(this).attr('id'));
var ck = $(this).prop("checked");
alert(id + ", " + ck); //The alert is displaying correctly all the values
var new_obj = id+"~"+ck; // here `~` is id/value separator
myList.push(new_obj);
})
movie.ListOfCBToDisplay = myList.join("^"); // here '^' is a separator
Then in your server side just split the string by using the ^
separator to get list of id/values, then split each of them by ~
. This is basically serializing manually the object.
EDIT
Another approach would be to copy all the needed values as <input type='hidden'>
to an hidden <form>
then use the JQuery serialize() on the form. Maybe you can use the current form to do so.
Upvotes: 1