ASP.NET MVC / Web API模型将项目绑定到集合

时间:2015-09-18 13:07:44

标签: c# extjs overloading asp.net-web-api model-binding

我使用Web API作为ExtJS数据存储的入口点,其中以批处理模式启用自动同步。这意味着我可以使用一个项目或一组项目来调用我定义的Web API方法,如下所述。

只有1项的案例:

{  
 "Category":"fsf",
 "Importance":10,
 "TaskNo":5467,
 "Id":"UnplannedTask-6",
 "StartDate":"2015-09-21T03:00:00+02:00",
 "EndDate":"2015-09-21T05:00:00+02:00",
 "Cls":"",
 "Name":"",
 "ResourceId":"18"
}

包含多个项目的案例:

[  
  {  
    "Category":"haer",
    "Importance":10,
    "TaskNo":5,
    "Id":"UnplannedTask-5",
    "StartDate":"2015-09-21T04:00:00+02:00",
    "EndDate":"2015-09-21T06:00:00+02:00",
    "Cls":"",
    "Name":"",
    "ResourceId":"14"
 },
 {  
  "Category":"fsf",
  "Importance":10,
  "TaskNo":5467,
  "Id":"UnplannedTask-6",
  "StartDate":"2015-09-21T03:00:00+02:00",
  "EndDate":"2015-09-21T05:00:00+02:00",
  "Cls":"",
  "Name":"",
  "ResourceId":"18"
  }
 ]

这对我的Web API造成了一些问题,因为我注意到重载有点棘手(也许是不可能的)。

以下是接受项目列表的Web API操作:

  [HttpPost]
  public async Task<dynamic> Update(IEnumerable<Appointment> appointments)
  {
   ...
  }

在这种场景中,它只接受一个:

 [HttpPost]
  public async Task<dynamic> Update(Appointment appointment)
  {
   ...
  }

现在,这两项行动都是单独的。当只有一个项目返回时,模型绑定是正确的。发送列表时的相同故事。到现在为止还挺好。 然而,无法知道是否将通过电线发送1个项目或10个项目。所以我必须能够支持这两个动作,但是重载不会以我经历过的方式工作 - 这意味着我一次只能使用一个动作。

所以我希望有一个解决方案,我可以使用模型绑定将1个项目的绑定转换为项目集合,这样我只能使用1个接受项目列表的操作。这是否可行,是否有任何示例(以及节省时间)?

1 个答案:

答案 0 :(得分:0)

感谢Peter Kellner,我已经调查了这个问题,看来ExtJS的数据存储编写器配置中有一个配置设置可以启用我的请求:

 proxy: {
    headers: { 'Accept': 'application/json' },
    type: 'ajax',
    api: {
        create: '/api/Appointments/Add',
        update: '/api/Appointments/Update',
        destroy: '/api/Appointments/Destroy'
    },
    reader: {
        type: 'json'
    },
    writer: {
        type: 'json',
        writeAllFields: true,
        allowSingle: false                 <------------------ That did the trick
    }
},