I have the following models in my ASP.NET Core code:
public class TestItem
{
public string Id { get; set; }
public string Name { get; set; }
public List<TestSubItem> SubItems { get; set; }
}
public class TestSubItem
{
public string Id { get; set; }
}
and the following method in my Controllers/TestController.cs:
// POST: Test/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([FromBody]TestItem item)
{
// Use item here...
return View(item);
}
I have the following JavaScript in my page:
var mySubItems = [{"Id": "1"}];
function submitForm() {
// myForm contains an Id textbox and a Name textbox
$("#myForm").submit();
};
function doPost() {
var testItem = {
Id: "2",
Name: "testName",
SubItems: mySubItems
};
$.ajax({
url: '@Url.Action("Create" ,"Test")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(testItem),
success: function (data) {
alert(data);
},
error: function (error) {
var x = error; //break here for debugging.
}
});
};
When I use doPost
, I always get 400 Bad Request
back from the server. submitForm
on the other hand works fine, but I don't know how to include mySubItems
in the data sent to the server.
What's the quickest way out of this?