2017-05-26 116 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(); 
     }