Pass JSON Object To MVC Controller as an Argument
Asked Answered
M

3

5

I have the following arbitrary JSON object(The field names may be changed).

  {
    firstname: "Ted",
    lastname: "Smith",
    age: 34,
    married : true
  }

-

public JsonResult GetData(??????????){
.
.
.
}

I know that I can define a class just like the JSON object with the same field names as the argument, But I would like my controller to accept arbitrary JSON object with different field names.

Matildamatilde answered 22/8, 2012 at 8:31 Comment(2)
Check this questionBenzofuran
Vadim, I knew this... The problem is that FormCollection doesn't accept the JSON...Matildamatilde
A
6

If you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.

    public string GetData()
    {
        // InputStream contains the JSON object you've sent
        String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();

        // Deserialize it to a dictionary
        var dic = 
          Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String, dynamic>>(jsonString);

        string result = "";

        result += dic["firstname"] + dic["lastname"];

        // You can even cast your object to their original type because of 'dynamic' keyword
        result += ", Age: " + (int)dic["age"];

        if ((bool)dic["married"])
            result += ", Married";


        return result;
    }

The real benefit of this solution is that you don't require to define a new class for each combination of arguments and beside that, you can cast your objects to their original types easily.

UPDATED

Now, you can even merge your GET and POST action methods since your post method doesn't have any argument any more just like this :

 public ActionResult GetData()
 {
    // GET method
    if (Request.HttpMethod.ToString().Equals("GET"))
        return View();

    // POST method 
    .
    .
    .

    var dic = GetDic(Request);
    .
    .
    String result = dic["fname"];

    return Content(result);
 }

and you can use a helper method like this to facilitate your job

public static Dictionary<string, dynamic> GetDic(HttpRequestBase request)
{
    String jsonString = new StreamReader(request.InputStream).ReadToEnd();
    return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
}
Articular answered 23/8, 2012 at 6:27 Comment(1)
Nice solution to avoid strongly typing all comms between client & server.Temper
S
1

Have a ViewModel with the same signature and use that as the argument type.Model binding will work then

public class Customer
{
  public string firstname { set;get;}
  public string lastname { set;get;}
  public int age{ set;get;} 
  public string location{ set;get;}
   //other relevant proeprties also
}

And your Action method will look like

public JsonResult GetData(Customer customer)
{
  //check customer object properties now.
}
Savory answered 22/8, 2012 at 16:50 Comment(0)
H
0

you can also use this in MVC 4

public JsonResult GetJson(Dictionary<string,string> param)
{
    //do work
}
Hutchison answered 15/1, 2014 at 8:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.