2017-05-26 3 views
0

Gibt es eine Möglichkeit, JSON-Daten an eine MVC5-Aktion zu senden? Keine WebAPI!POST JSON zu ASP.NET MVC5? (NICHT Web-API)

Das Problem ist: Meine Aktion wird aufgerufen, aber alle Eigenschaften des eingehenden Modells sind null.

Modell:

using Newtonsoft.Json; 

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

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

Aktion ist:

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

Ich habe Fiddler wurde mit der Anfrage zu simulieren. Meine POST-Anfrage sieht wie folgt aus:

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

Und der Körper sieht wie folgt aus:

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

Also, die Frage wieder: wie kann ich die JSON auf eine Aktion POST? In meinem Fall sind alle Eigenschaften des Modells null.

+0

FromBody Attribut nicht verfügbar in nicht WebAPI:/ – Dima

+1

Sie haben Recht. Entschuldigen Sie – Nkosi

Antwort

0

benutze ich nur diese Codes und es funktionierte auf MVC5 Aktion gut, aber sicher, dass Sie, ohne dass Content-Type : application/json in Ihren POST-Request-Header verwenden, es wird nicht korrekt funktionieren und das Modell wird noch null

public class DemoModel 
    { 

     public string a { get; set; } 


     public string b { get; set; } 
    } 

[HttpPost] 
     public ActionResult Index(DemoModel model) 
     { 

      return View(); 
     }