Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex type is getting null in a ApiController parameter

I don´t know why my parameter "ParametroFiltro Filtro" is getting null, the other parameters "page" and "pageSize" is getting OK.

public class ParametroFiltro {     public string Codigo { get; set; }     public string Descricao { get; set; } } 

My ApiController Get method:

public PagedDataModel<ParametroDTO> Get(ParametroFiltro Filtro, int page, int pageSize) 

My ajax call:

var fullUrl = "/api/" + self.Api; $.ajax({     url: fullUrl,     type: 'GET',     dataType: 'json',     data: { Filtro: { Codigo: '_1', Descricao: 'TESTE' }, page: 1, pageSize: 10 },     success: function (result) {         alert(result.Data.length);         self.Parametros(result.Data);     } }); 
like image 614
will Avatar asked Oct 16 '12 13:10

will


2 Answers

You are trying to send a complex object with GET method. The reason this is failing is that GET method can't have a body and all the values are being encoded into the URL. You can make this work by using [FromUri], but first you need to change your client side code:

$.ajax({     url: fullUrl,     type: 'GET',     dataType: 'json',     data: { Codigo: '_1', Descricao: 'TESTE', page: 1, pageSize: 10 },     success: function (result) {         alert(result.Data.length);         self.Parametros(result.Data);     } }); 

This way [FromUri] will be able to pick up your complex object properties directly from the URL if you change your action method like this:

public PagedDataModel<ParametroDTO> Get([FromUri]ParametroFiltro Filtro, int page, int pageSize) 

Your previous approach would rather work with POST method which can have a body (but you would still need to use JSON.stringify() to format body as JSON).

like image 90
tpeczek Avatar answered Oct 14 '22 15:10

tpeczek


Provide the contentType property when you make the ajax call. Use JSON.stringify method to build the JSON data to post. change the type to POST and MVC Model binding will bind the posted data to your class object.

var filter = { "Filtro": { "Codigo": "_1", "Descricao": "TESTE" },                                                 "page": "1", "pageSize": "10" };  $.ajax({     url: fullUrl,     type: 'POST',     dataType: 'json',     contentType: 'application/json',     data: JSON.stringify(filter),     success: function (result) {         alert(result.Data.length);         self.Parametros(result.Data);     } }); 
like image 42
Shyju Avatar answered Oct 14 '22 15:10

Shyju