Ryan Dooley
Ryan Dooley

Reputation: 254

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..

Upvotes: 0

Views: 6495

Answers (2)

ThomW
ThomW

Reputation: 121

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

} 

Upvotes: 4

maccettura
maccettura

Reputation: 10819

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.

Upvotes: 1

Related Questions