I'm trying to post a JavaScript data object with the following:
$.post(frm.attr("action"), data, function(res)
{
// do some stuff
}, "json");
where 'data' takes the structure of
data
- panelId
- siteId
- ConfiguredFactsheetId // this is an array of CheckBox ids that correspond to ConfiguredFactsheets
- 123
- 234
- 345
With this, both site & panel are correctly instantiated & bound with their data but the List object is null.
public JsonResult Edit(Site site, Panel panel, List<ConfiguredFactsheet> configuredFactsheets)
{
// do stuff
return Json(success);
}
Now, I realise that my 'data' object's ConfiguredFactsheetId property is just an array of id values. Do I need to specify that each value corresponds to a configuredFactsheetId property of my ConfiguredFactsheet object? If so, my data object would take a form similart to
data
- panelId
- siteId
- ConfiguredFactsheet // this is an array of CheckBox ids that correspond to ConfiguredFactsheets
- ConfiguredFactsheetId:123
- ConfiguredFactsheetId:234
- ConfiguredFactsheetId:345
but this obviously won't work because every time I add a new ConfiguredFactsheetId to the object, it'll just overwrite the previous one.
I know I can do this if I built a query string of the form
"&ConfiguredFactsheet[i].configuredFactsheetId = " + configuredFactsheetId;
but I'd like to contain everything in a single data object
Any suggestions? Do I need to explain anything (probably everything!) more clearly?
Thanks
Dave
In the end, this worked:
var valuesArray = objCheckBoxes.map(function()
{
return $.getAttributes($(this));
});
var obj = new Array();
$.each(valuesArray, function(item) { obj.push($(this)[0]); });
$.each(obj, function(i)
{
// basically I take the rule where you need to append
// the index to the type, and I apply it here.
data["configuredFactsheets[" + i + "].configuredFactsheetId"] = $(this).attr("configuredFactsheetId");
});
Note: read about $.getAttributes
An alternative is to post:
?myValues=1&myValues=2&myValues=3
And accept it as an IEnumerable
public ActionResult DoSomething(IEnumerable<int> myValues) {
...
来源:https://stackoverflow.com/questions/2402434/model-bind-to-a-list-when-posting-javascript-data-object