Pass JSON Object To MVC Controller as an Argument

后端 未结 3 2153
时光取名叫无心
时光取名叫无心 2020-12-03 19:33

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

  {
    firstname: \"Ted\",
    lastname: \"Smith\",
    age: 34,
    married : t         


        
3条回答
  •  一生所求
    2020-12-03 19:48

    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>(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 GetDic(HttpRequestBase request)
    {
        String jsonString = new StreamReader(request.InputStream).ReadToEnd();
        return Newtonsoft.Json.JsonConvert.DeserializeObject>(jsonString);
    }
    

提交回复
热议问题