0

I've an ASP.Net MVC 4 application that I'm porting to ASP.Net Core 3.0 MVC.

I'm trying to port this method

[HttpPost]
public ActionResult DoSave(
  [Bind(Prefix = "new")]IEnumerable<C_Data> newItems,
  [Bind(Prefix = "updated")]IEnumerable<C_Data> updatedItems,
  [Bind(Prefix = "deleted")]IEnumerable<C_Data> deletedItems))
{
}

In the post AJAX (in JavaScript from the web browser) I'm sending the values as JSON like this

{
  "new[0].Id":3,
  "new[0].SID":"00000000-0000-0000-0000-000000000000",
  "new[0].Name":"asd"
}

Here's the C_Data class

public class C_Data
{
    [Key]
    public int Id { get; set; }

    public Guid SID { get; set; }

    [Required]
    [MaxLength(40)]
    public string Name { get; set; }
}

But the three parameters are empty when this action is executed.

Here's the error I get in the ModelState

"The JSON value could not be converted to C_Data"

Anyone please can tell me how to port this method?

Thank you.

PD: This action is in an MVC controller not an API controller.

vcRobe
  • 1,671
  • 3
  • 17
  • 35
  • Possible duplicate of [How to use Bind Prefix?](https://stackoverflow.com/q/1317523/11683) – GSerg Oct 03 '19 at 14:44
  • 1
    you know that `BindAttribute` is for forms not json? you json should be `{"newItems":[{"Id" : 3,"SID":...}], "updatedItems":[...]}` – Selvin Oct 03 '19 at 14:48

2 Answers2

0

Here's a link that should help.

It looks like you should be able to use C_Data object, put it in an array, and stringify it in the AJAX call, receive an IEnumerable.

0

For Asp.Net Core, there are two ways to bind the model, ModelBinding and JsonInputFormatter. For sending request with json, it will use JsonInputFormatter and Bind will not work.

In general, I would suggest you try option below:

  1. Controller Action

    [HttpPost]
    public ActionResult DoSave([FromBody]ItemModel itemModel)
    {
        return Ok("Worked");     
    }
    
  2. Model

    public class ItemModel
    {
        public IEnumerable<C_Data> NewItems { get; set; }
        public IEnumerable<C_Data> UpdatedItems { get; set; }
        public IEnumerable<C_Data> DeletedItems { get; set; }
    
    }
    
  3. Request Json

    {
        "newItems":[{
            "Id":3,
            "SID":"00000000-0000-0000-0000-000000000000",
            "Name":"asd"
        }]
    }
    
Edward
  • 28,296
  • 11
  • 76
  • 121