Model Bind to a List<> when Posting JavaScript Data Object

冷暖自知 提交于 2019-12-08 05:26:39

问题


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


回答1:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!