Check my code shown below. I am posting some json to a controller method. And I want to receive the values in C# model class called MenuItems; but the problem is: I am able to post data to my controller, but all of my 'MenuItems' return null. Data is not being assigned properly. How can I fix it?
AJAX:
var obj = '[{ "text": "wewer", "target": "_self", "children": [{ "text": "wer", "target": "_top" }] }]';
$.ajax({
type: "POST",
url: "/Custom/SaveMenu",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DemoWeb.ViewModels
{
public class MenuItems
{
public string text { get; set; }
public string target { get; set; }
public List<Child> children { get; set; }
}
public class Child
{
public string text { get; set; }
public string target { get; set; }
}
}
Controller:
[HttpPost]
public JsonResult SaveMenu(MenuItems menuItems)
{
//'menuItems' this returns null for all properties
//return Json("pokay");
}
public JsonResult SaveMenu(IEnumerable<MenuItems> menuItems)(note also, you have already stringified it so you don't need to useJSON.stringify()to do it again)[and]so its an object, not a collectiondata: obj,and removedata: JSON.stringify(obj),