开发者

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

开发者 https://www.devze.com 2022-12-22 01:51 出处:网络
I\'m trying to post a JavaScript data object with the following: $.post(frm.attr(\"action\"), data, function(res)

I'm trying to post a JavaScript data object with the following:

$.post(frm.attr("action"), data, function(res)
{
    // do some stuff
}, "json");

开发者_JAVA百科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) {
    ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号