Dudemanword
Dudemanword

Reputation: 704

What does Web API need to bind models?

Using angular, I send an HTTP request

$scope.addFiles = function (files) {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            $http.post('/api/files/addFiles', JSON.stringify({ testName: "test", someRandomCrap:"asdf"}));
        }
    }

I receive the request properly in my controller. However, the response is null: Null Request :(

After verifying that the content header is alright and the information was actually sent, I replaced the sample object with a generic object:

It Works!

Lo and behold. It works! From this, my guess is that Web API could not bind to my object. Which brings me to my question: What does Web API need to bind to an object?

TestObject:

public class TestObject
{
    string testName { get; set; }
    string someRandomCrap { get; set; }
}

Upvotes: 3

Views: 99

Answers (2)

Khanh TO
Khanh TO

Reputation: 48972

Try this:

$scope.addFiles = function (files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        $http.post('/api/files/addFiles', { testName: "test", someRandomCrap:"asdf"});
    }
}

Two things:

  • In asp.net api, the whole request body is bound to a parameter so that we don't need to specify a property name in the request body. Have a look at this: web api put is recognizing query strings but not body
  • Don't need JSON.stringify otherwise it will treat your whole object as a string. In your second picture, the fileName is of type string

Also try making your properties public:

public class TestObject
{
    public string testName { get; set; }
    public string someRandomCrap { get; set; }
}

Upvotes: 2

Fals
Fals

Reputation: 6839

Just need the object Itself:

$scope.addFiles = function (files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        $http.post('/api/files/addFiles',{ fileName: { testName: "test", someRandomCrap:"asdf"}});
    }
}

Upvotes: 0

Related Questions