dopoto
dopoto

Reputation: 1264

POSTing complex JSON to ASP.NET Core Controller

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?

Upvotes: 3

Views: 4073

Answers (1)

Jeff S
Jeff S

Reputation: 7484

Including [ValidateAntiForgeryToken] on your controller is causing the problem. You need to include the token when you post the data. MVC automatically includes it the form which is why submitForm() works.

The challenge is that I do not know how to make it work with JSON data getting posted. You might be able to by adding the following into testItem:

__RequestVerificationToken: $('input[name="__RequestVerificationToken"]', form).val()

For more information, check out include antiforgerytoken in ajax post ASP.NET MVC

Upvotes: 6

Related Questions