2016-07-04 75 views
2

我在我的ASP.NET核心代码以下型号:发布复杂的JSON到ASP.NET核心控制器

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; } 
} 

,并在我的控制器/ TestController.cs下面的方法:

// POST: Test/Create 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public IActionResult Create([FromBody]TestItem item) 
    { 
     // Use item here... 
     return View(item); 
    } 

我有以下的JavaScript在我的网页:

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. 
     } 
    }); 
}; 

当我使用doPost,我总是g ^从服务器返回400 Bad Request。另一方面submitForm工作正常,但我不知道如何在发送到服务器的数据中包含mySubItems

什么是最快的方法呢?

+0

'网址: '@ Url.Action( “创建”, “测试”)','。你确定这有效吗? –

+0

是的,网址是好的 – marin

回答

5

在控制器上包含[ValidateAntiForgeryToken]会导致问题。发布数据时需要包含令牌。 MVC自动将它包含在submitForm()工作的原因中。

挑战是我不知道如何使它与JSON数据一起工作。您可能能够通过添加以下到testItem:

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

欲了解更多信息,请include antiforgerytoken in ajax post ASP.NET MVC

相关问题