如果你想傳遞自定義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操作方法,因爲你的帖子方法沒有任何參數的任何更多的只是這樣的:
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);
}
檢查[this](http://stackoverflow.com/questions/5022958/passing-dynamic-json-object-to-c-sharp-mvc-controller)問題 – vadim
Vadim,我知道這...問題是FormCollection不接受JSON ... –