ekenman
ekenman

Reputation: 995

Format JSon so that mvc4 controller method can parse it

My controller Action:

       [HttpPost]
        public ActionResult H80Count(IEnumerable<H80SearchCriteria> model)
        {
             do some stuff and return Json;
        }

My model:

    public class H80SearchCriteria
    {
        public int ID { get; set; }
        public int Operator { get; set; }
        public string FieldID { get; set; }
        public string Kriterie { get; set; }

    }

My Javascript:

    var SearchCriteria = [];
    var i = 0;
    $('#tableSearchValues > tbody').find('tr').each(function () {
        i += 1;

        var row = {
            ID : i,
            Operator : $(this).data('operator'),
            FieldID : $(this).data('fieldid'),
            Kriterie: $(this).data('kriterie')
        };

        SearchCriteria.push(row);
    });
    var url = '/MyController/H80Count';
    var data = JSON.stringify(SearchCriteria) ;

    $.ajax({
        type: 'POST',
        url: url,
        data: data,
    etc...

The Json that is passed looks like this:

[{"ID":1,"Operator":1,"FieldID":1,"Kriterie":11211},{"ID":2,"Operator":1,"FieldID":1,"Kriterie":11211}]

I can't see why it is not parsed correctly. What am I missing?

Upvotes: 1

Views: 177

Answers (2)

Anto Subash
Anto Subash

Reputation: 3215

try this instead of IEnumerable use array and place [FromUri] or [FromBody] which looks for values in the Uri or Body of the request.

    [HttpPost]
    public ActionResult H80Count([FromUri] H80SearchCriteria[] model)
    {
         do some stuff and return Json;
    }

and dont forget to set the traditional ajax settings as true

$.ajax({
        type: 'POST',
        url: url,
        data: data,
        traditional: true
        });

Upvotes: 0

Felipe Miosso
Felipe Miosso

Reputation: 7339

I think you forgot the contentType: 'application/json' on ajax function.

It works for me.

Upvotes: 1

Related Questions