How can I send two objects via ajax to a web api?

1

I need to send two objects to the post and update methods to an Api web, I work with c #, webapi, mvc. He is not taking it.

var album = {
    nombre: "PowerAge",
    Fecha: "011/10/1979"
}
var user = {
    Name: "Rick"
    area: "operaciones"
}

$.ajax(
{
    url: "samples/PostAlbum",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ album: album, user: user }),
     success: function (result) {
        alert(result);
    }
});

Api

[HttpPost]
public IHttpActionResult PostAlbum(album item, user itemuser)
{

}
    
asked by Erwing 16.02.2016 в 17:35
source

1 answer

2

Try using

$.ajax(
{
   url: "samples/PostAlbum",
   type: "POST",
   contentType: "application/json",
   data: { item: album, itemuser: user },
   success: function (result) {
       alert(result);
    }
});

As you will see in the json that you send as data must match the parameters of webapi ,

data: { item: album, itemuser: user },

that's why I defined item and itemuser that match the parameters of the action you invoke.

On the other hand if it is webapi the url should be: api/samples

Defining the action is not necessary because with the verb of http reaches. This applies if it is a controller that inherits from ApiController , instead if it is a simple controller you should use:

url: '@Url.Action("PostAlbum")',

let @Url.Action() from the view be who defines the url.

    
answered by 16.02.2016 / 17:57
source