通过JSON对象要MVC控制器作为参数 [英] Pass JSON Object To MVC Controller as an Argument

查看:118
本文介绍了通过JSON对象要MVC控制器作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following arbitrary JSON object(The field names may be changed).

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

-

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

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

I know that I can define a class just like the JSON object with the same field names as the argument, But I would like my controller to accept arbitrary JSON object with different field names.

推荐答案

如果你想通过自定义的JSON对象MVC行动,那么你可以使用这个解决方案,它的工作原理就像一个魅力。

If you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.

    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;
    }

该解决方案的真正的好处是,你不需要定义一个新的类的参数每个组合和旁边,您可以轻松地投你的对象到其原始的类型。

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.

更新时间:

现在,你甚至可以合并您的GET和POST操作方法,因为您的文章的方法没有任何说法更多的只是这样的:

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 :

 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);
 }

,你可以使用一个辅助方法如下,以方便你的工作。

and you can use a helper method like this to facilitate your job

public static Dictionary<string, dynamic> GetDic(HttpRequestBase request)
{
    String jsonString = new StreamReader(request.InputStream).ReadToEnd();
    return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
}

这篇关于通过JSON对象要MVC控制器作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆