Bick
Bick

Reputation: 18511

asp mvc ajax call - json parameter received as null

I call a mvc controller using ajax using :

 var ajaxOptions = { url: url, type: 'POST', contentType: 'application/json', 
                     data: JSON.stringify(data) };

I send the following JSON in data

data = "{"TagList":["AA","BB","CCC","DDDD"]}"

In my controller the following method is called

[HttpPost]
public async Task<JsonResult> Update(TagItem tagItem)

and I get TagItem.TagList = null

public class TagItem
{
    public List<string> TagList { get; set; }
}

Upvotes: 0

Views: 2304

Answers (2)

PSL
PSL

Reputation: 123739

You are missing the tagItem wrapper in JSON.

data = {"tagItem":{"TagList":["AA","BB","CCC","DDDD"]}};

var ajaxOptions = 
             { url: url, 
               type: 'POST', 
               contentType: 'application/json; charset=utf-8', 
               data: JSON.stringify(data) 
              };

Try this for instance:-

  var data = { "tagItem": { "TagList": ["AA", "BB", "CCC", "DDDD"]} };

    $.ajax({
        type: 'POST',
        url: "home/test",
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'
    });

Upvotes: 4

webdeveloper
webdeveloper

Reputation: 17288

Try this with contentType:

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: url,
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8'
});

Added:

As @PSL found OP lost tagItem, after wrapping current data with it, code must work.

Upvotes: 2

Related Questions