2012-08-22 131 views
5

我有以下任意JSON對象(字段名稱可能會更改)。將JSON對象傳遞給MVC控制器作爲參數

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

-

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

我知道我可以定義一個類一樣,使用相同的字段名作爲參數JSON對象,但我想我的控制器,以接受不同的任意JSON對象字段名稱。

+0

檢查[this](http://stackoverflow.com/questions/5022958/passing-dynamic-json-object-to-c-sharp-mvc-controller)問題 – vadim

+1

Vadim,我知道這...問題是FormCollection不接受JSON ... –

回答

6

如果你想傳遞自定義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); 
} 
+1

很好的解決方案,以避免強烈鍵入客戶端和服務器之間的所有通信。 – Dermot

1

有一個視圖模型具有相同簽名,並用其作爲參數type.Model綁定將工作,然後

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 
} 

而且動作方法看起來就像

public JsonResult GetData(Customer customer) 
{ 
    //check customer object properties now. 
} 
0

您還可以在MVC 4

使用
public JsonResult GetJson(Dictionary<string,string> param) 
{ 
    //do work 
} 
+1

param對我來說總是一個空的對象... – jjxtra

相關問題