简体   繁体   中英

$http.post posts null parameter to mvc.net api

I have this on my js

var modelo = {
    Estatus: 2,
    IdVet: 1                   
};

$http.post('/AdminV2/Vet/ActualizarEstatus', modelo)
    .then(function (res) {

    });

And this on my .cs

[HttpPost]
public JsonResult ActualizarEstatus(ActualizarEstatus estatus)
{
    if (estatus == null)
    {
        return JsonResultBool(false);
    }
    return JsonResultBool(true);
}

public class ActualizarEstatus
{
    public int Estatus { get; set; }
    public int IdVet { get; set; }
}

And the parameter "estatus" is always null. What am I doing wrong?

EDIT: Corrected the example

Couple of things -

  1. Make sure your url is right. I see your action method name as - ActualizarEstatus , but you are calling /AdminV2/Vet/ObtenerVets in your ajax call. That is not right, so correct it.

  2. You have to use estatus variable name to pass data through ajax.

Please use following code, I tested it -

var modelo = {
    Estatus: 2,
    IdVet: 1
};

$.ajax({
    url: "/Home/ActualizarEstatus", // this is my local url, change it with your valid url.
    type: "POST",
    data: JSON.stringify({ estatus: modelo }),
    contentType: "application/json; charset=utf-8",
    success: function(result) {
        console.log(result);
    }
});

When i use above code, I get following output -

在此处输入图片说明

In your JS side make sure that you wrap your result in a Property called estatus before assigning to var modelo (the same name should be used in both C# and JS). Also Stringify this property before sending in $http.post

You have to stringify your model. This wrapper helps your model to make json.

$http.post('/AdminV2/Vet/ObtenerVets', JSON.stringify(modelo))
.then(function (res) {

});

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