asp.net 5 / mvc 6 / model binder / angular

333 Views Asked by At

I do not know because when I do a post by angular, objects are not populated, such as categories or status. Just the product. However, note that the Request.Form list, the information is there. The binder is not performed correctly. What am I doing wrong? Is it any web api configuration? I've tried sending data via application/json, [frombody] ... I'm out of options. Thanks in advance.

var product = {
  id: 1,
  name: "Name",
  categories: [
    { id: 1, name: "name 1" },
    { id: 2, name: "name 2" }
  ],
  status: { id: 1, name: "active" }
};

var config: ng.IRequestConfig;
config = { url: "", method: "POST", headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } };

self.$http.post("api/produto", $.param(product), config)
.success(function () {
  alert("OK");
});

    [HttpPost]
    public ProductInfo Post(ProductInfo item)
    {
        return item;
    }


model image

request image

4

There are 4 best solutions below

0
Thayson Fenandes Do Nascimento On

try this:

$http({
        url: "api/produto",
        method: "POST",
        data: product,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
0
sjokkogutten On

Or you could use the shortcut method:

$http.post('api/produto', data).then(successCallback, errorCallback);
0
Maxime Rouiller On

Here's what I would try

var product = {
  id: 1,
  name: "Name",
  categories: [
    { id: 1, name: "name 1" },
    { id: 2, name: "name 2" }
  ],
  status: { id: 1, name: "active" }
};

var config: ng.IRequestConfig;
config = { url: "", method: "POST", headers: { 'Content-Type': 'application/json;charset=utf-8;' } };

self.$http.post("api/produto", product, config)
.success(function () {
  alert("OK");
});

What is different is that I send the actual JavaScript object and it will be serialized as JSON. Web API will be able to deserialize the JSON into a pure C# object.

Trying to match key/value pair is normally just madness on complex objects.

0
Eduardo Tolino On

There was no way to do it.

Either I create a custom model binder, or I'll have the new web api 6 mvc always use the frombody and force the ship by json.

At least that's what I did with my tests. It worked just sending json and using frombody.

The documentation, really changed bind the web api 2 for this new integrated model to MVC.