简体   繁体   中英

Post JSON to MVC controller

I've looked at various questions and answers, however I am only partially successful.

The View is passing this JSON:

{JsonInput: [["208-01", "003158"]], JobNumber: "test"}

$.ajax({
   type: "POST",
   url: "/Dash/SavePickups",
   contentType: 'application/json',
   dataType: "json",
   data: JSON.stringify({
       JsonInput: final,
       JobNumber:"test"
       }),

The Json String above is sent to the controller at /Dash/SavePickups

  [System.Web.Http.Route("Dash/SavePickups/{JsonInput}")]
    public JsonResult SavePickups(object[][] JsonInput)
    {
        var FailResult = new { Success = "False", Message = "Error" };
        var SuccessResult = new { Success = "True", Message = "Pickups Scheduled Successfully." };

       return Json(SuccessResult, JsonRequestBehavior.AllowGet);

    } 

Only part of the JSON string is passed to the JsonInput. In Debug I see the JsonInput Object, with the Obj array 208-01 and 003158.

Why isn't JobNumber included, I can see in chrome Network POST its part of the JSON string sent to the controller..

Continuing maccettura's answer - Your issue is with deserializing the JSON into an object. Your given JSON is formatted as { JsonInput : ["1234","5667"], JobNo : "Test" }

Which has one possible data structure of

List<string> , String 

which will not deserialize into a 'sqaure' object such as

object [][]

I'd recommend making a model for your json that looks like this:

 public class SavePickupsModel 
{
     public List<string> JsonInput {get; set;}
     public string JobNo {get; set; }
}

Then use that model as input into your method:

[HttpPost]
[System.Web.Http.Route("Dash/SavePickups/{JsonInput}")]
public JsonResult SavePickups(SavePickupsModel JsonInput)
{
    var FailResult = new { Success = "False", Message = "Error" };
    var SuccessResult = new { Success = "True", Message = "Pickups Scheduled Successfully." };

   return Json(SuccessResult, JsonRequestBehavior.AllowGet);

} 

I would start by tagging your controller with the [HttpPost] attribute

[HttpPost]
[System.Web.Http.Route("Dash/SavePickups/{JsonInput}")]
public JsonResult SavePickups(object[][] JsonInput)
{

}

I would also point out that your parameter for the action ( object[][] JsonInput ) does not look right to me. You will likely find that the json does not deserialize to that object type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM