如果您想将自定义JSON对象传递给MVC操作,则可以使用此解决方案,它的工作原理很吸引人。
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; }该解决方案的真正好处是,您不需要为每个参数组合定义一个新类,并且除此之外,您可以轻松地将对象转换为其原始类型。
更新
现在,您甚至可以合并GET和POST操作方法,因为您的post方法不再像这样具有任何参数:
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); }您可以使用这样的帮助方法来简化您的工作
public static Dictionary<string, dynamic> GetDic(HttpRequestbase request){ String jsonString = new StreamReader(request.InputStream).ReadToEnd(); return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);}


