将JSON对象作为参数传递给MVC控制器

5
我有以下任意的JSON对象(字段名称可能会改变)。
  {
    firstname: "Ted",
    lastname: "Smith",
    age: 34,
    married : true
  }

-

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

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

请查看此问题:传递动态JSON对象到C# MVC控制器 - vadim
1
Vadim,我知道这个问题...问题在于FormCollection不接受JSON... - Ali No
3个回答

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操作方法,因为您的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

使用具有相同签名的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.
}

0

你也可以在MVC 4中使用这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接