Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.</p> <pre><code> 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&lt;Dictionary&lt;String, dynamic&gt;&gt;(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; } </code></pre> <p>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.</p> <p><strong>UPDATED</strong></p> <p>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 :</p> <pre><code> 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); } </code></pre> <p>and you can use a helper method like this to facilitate your job</p> <pre><code>public static Dictionary&lt;string, dynamic&gt; GetDic(HttpRequestBase request) { String jsonString = new StreamReader(request.InputStream).ReadToEnd(); return Newtonsoft.Json.JsonConvert.DeserializeObject&lt;Dictionary&lt;string, dynamic&gt;&gt;(jsonString); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload