2017-05-26 114 views
0

有没有办法将JSON数据发布到MVC5动作? 不是WebAPI!POST JSON到ASP.NET MVC5? (不是web API)

问题是:我的动作被调用,但传入模型的所有属性都为null。

型号:

using Newtonsoft.Json; 

[JsonObject()] 
[Serializable()] 
public class DemoModel 
{ 
    [JsonProperty()] 
    public string a { get; set; } 

    [JsonProperty()] 
    public string b { get; set; } 
} 

行动是:

[HttpPost()] 
public ActionResult demoaction(DemoModel model) 
{ 
    //model.a here is null, should be "AAA" 
    //model.b here is null, should be "BBB" 
} 

我一直在使用招模拟请求。我的POST请求是这样的:

POST http://localhost:9000/demoaction HTTP/1.1 
Host: localhost:9000 
Connection: keep-alive 
Accept: */* 
Content-Type: application/json 
Content-Length: 60 

而且身体看起来是这样的:再次

{"a":"AAA","b":"BBB"} 

所以,问题:我如何可以张贴JSON一个动作?在我的情况下,模型的所有属性都是null。

+0

FromBody属性不适用于非WebAPI:/ – Dima

+1

您是对的。我很抱歉 – Nkosi

回答

0

我只是使用这些代码,并在MVC5行动 工作得很好,但要确保你使用的是在您的POST请求头Content-Type : application/json没有,这将无法正常工作和车型还将空

public class DemoModel 
    { 

     public string a { get; set; } 


     public string b { get; set; } 
    } 

[HttpPost] 
     public ActionResult Index(DemoModel model) 
     { 

      return View(); 
     }