【问题标题】:Model Bind to a List<> when Posting JavaScript Data Object发布 JavaScript 数据对象时模型绑定到 List<>
【发布时间】:2010-03-08 15:35:52
【问题描述】:

我正在尝试使用以下内容发布 JavaScript 数据对象:

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

“数据”的结构是

data
 - panelId
 - siteId
 - ConfiguredFactsheetId // this is an array of CheckBox ids that correspond to ConfiguredFactsheets
   - 123
   - 234
   - 345

这样,站点和面板都正确实例化并与其数据绑定,但 List 对象为空。

public JsonResult Edit(Site site, Panel panel, List<ConfiguredFactsheet> configuredFactsheets)
{
    // do stuff
    return Json(success);
}

现在,我意识到我的“数据”对象的 ConfiguredFactsheetId 属性只是一个 id 值数组。我是否需要指定每个值对应于我的 ConfiguredFactsheet 对象的一个​​ configuredFactsheetId 属性?如果是这样,我的数据对象将采用类似于

的形式
data
 - panelId
 - siteId
 - ConfiguredFactsheet // this is an array of CheckBox ids that correspond to ConfiguredFactsheets
   - ConfiguredFactsheetId:123
   - ConfiguredFactsheetId:234
   - ConfiguredFactsheetId:345

但这显然行不通,因为每次我向对象添加新的 ConfiguredFactsheetId 时,它都会覆盖前一个。

我知道如果我构建了一个表单的查询字符串,我可以做到这一点

"&ConfiguredFactsheet[i].configuredFactsheetId = " + configuredFactsheetId;

但我想将所有内容都包含在一个数据对象中

有什么建议吗?我需要更清楚地解释任何事情(可能是所有事情!)吗?

谢谢

戴夫

【问题讨论】:

  • AFAIK 如果你有一个名为ConfiguredFactsheet 的数组,你应该有参数名称'configuredFactsheet. If it stores list of ints, it could be IEnumerable. So use public JsonResult Edit(IEnumerable configuredFactsheet)`。 panelId是如何转化为panel的?你有自己的 ModelBinder 吗?

标签: javascript jquery asp.net-mvc model-binding


【解决方案1】:

最后,这成功了:

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");
});

注意:阅读$.getAttributes

【讨论】:

    【解决方案2】:

    另一种方法是发帖:

    ?myValues=1&myValues=2&myValues=3
    

    并接受它作为 IEnumerable

    public ActionResult DoSomething(IEnumerable<int> myValues) {
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 2017-04-06
      • 2017-08-07
      • 2012-03-15
      • 2011-05-28
      相关资源
      最近更新 更多