Vlado Pandžić
Vlado Pandžić

Reputation: 5048

Web API model binding not working

Why is Web API model binding so complicated by default: I tried a lot of combinations but none of them seem to work. This is ajax request:

var dataString = JSON.stringify({
            request: Request
        });
var request = Request;
$.ajax({
        type: "POST",
        data: '='+dataString,
        // contentType: 'application/x-www-form-urlencoded',
        contentType: "application/json; charset=utf-8",
        dataType: "json",

This is controller:

public AccResultObject Post(string jezik, string page, string size, string sort,AccRequestViewModel model)

This is AccRequestViewModel

public class AccRequestViewModel
{
    public AccRequestObject request { get; set; }
}

and this is AccRequestObject:

public class AccRequestObject
    {

        public int FM { get; set; }
        public int Budget { get; set; }
        public string WebCatID { get; set; }


        public int Distance { get; set; }
    }

Whatever I do, controller gets null value.

I tried this also. It seems very logical:

 var dataString = JSON.stringify({
            request: Request
         });
 $.ajax({
        type: "POST",
        data: dataString, ...

and controller receives AccRequestObject:

  public AccResultObject Post(string jezik, string page, string size, string sort,[FromBody] AccRequestObjectmodel)

It works great except this small problem. Values are not binded.

Upvotes: 1

Views: 3973

Answers (2)

bbsimonbb
bbsimonbb

Reputation: 29002

In the C#, make sure your properties are public properties, not fields.

public class MyBindingModel
{
    public string myProp{ get; set; }
}

Upvotes: 1

Mike_G
Mike_G

Reputation: 16502

Make sure the properties of each object you are creating in javascript match exactly to the code model. If a property name is uppercase in the code model, it needs to be uppercase in the js. Other than that, to post a model with jquery to a Web Api controller is pretty simple:

//code model
public class MyModel{
    public int MyProperty{get;set;}     
}

//js
$.ajax({
        contentType: "application/json",
        dataType: 'json',
        url: 'http://api/to/my/controller',
        data: JSON.stringify({MyProperty: 1}),
        type: "POST"
    });

Upvotes: 2

Related Questions