【问题标题】:Pass JSON Object To MVC Controller as an Argument将 JSON 对象作为参数传递给 MVC 控制器
【发布时间】:2012-08-22 08:31:55
【问题描述】:

我有以下任意 JSON 对象(字段名称可能会更改)。

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

-

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

我知道我可以定义一个类,就像 JSON 对象一样,具有与参数相同的字段名称,但我希望我的控制器接受具有不同字段名称的任意 JSON 对象。

【问题讨论】:

  • 检查this问题
  • Vadim,我知道这个...问题是 FormCollection 不接受 JSON...

标签: asp.net-mvc json jsonresult


【解决方案1】:

如果你想将自定义 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);
}

【讨论】:

  • 避免在客户端和服务器之间强烈键入所有通信的好解决方案。
【解决方案2】:

拥有一个具有相同签名的 ViewModel 并将其用作参数类型。然后模型绑定将起作用

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
}

你的 Action 方法看起来像

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

【讨论】:

    【解决方案3】:

    你也可以在 MVC 4 中使用它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 2012-01-16
      • 1970-01-01
      相关资源
      最近更新 更多