简体   繁体   中英

ASP.NET MVC/Web API model binding item to collection

I am using Web API as the entry points for an ExtJS data store, where autosync is enabled in batch mode. This means that my defined Web API method can either be called with just 1 item or a collection of items, as described below.

Case with only 1 item:

{  
 "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"
}

Case with multiple items:

[  
  {  
    "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"
  }
 ]

This is causing some issues for my Web API, as I have noticed overloading is somewhat tricky (perhaps impossible).

Here is the Web API action that accepts a list of items:

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

Here it is once more in the scenario that it only accepts one:

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

Now, both actions work individually. When only one item comes back, the model binding is correct. Same story for when a list is sent back. So far so good. It is however impossible to know whether 1 item or 10 items will be sent across the wire. So I have to be able to suppport both actions, but overloading doesn't work in this way I have experienced - which means I can only use one action at a time.

So I was hoping for a solution where I could use model binding to convert the binding for 1 item to a collection of items, so that I can use only 1 action that accepts a list of items. Is this possible and are there any examples (and time savers) available?

Thanks to Peter Kellner, I have investigated this issue and it appears there's a configuration setting in ExtJS's data store writer config that enables my request:

 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
    }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM