Asp.net MVC5 json值绑定到scafolding

时间:2014-07-06 17:39:58

标签: c# jquery asp.net asp.net-mvc json

我正在使用SyncFusion Asp.Net MVC网格,在此我试图在服务器端过滤并且发送到服务器的json如下

但在ViewModel中,对象属性为null而不是绑定

的Json

{"select":["Area","Id"],"where":[{"isComplex":false,"field":"Area","operator":"startswith","value":"test","ignoreCase":true}],"sorted":[{"name":"Area","direction":"ascending"}]}

我已经创建了如下模型,这是传递给控制器​​但它没有绑定。

 public class UserViewModel
    {
        public int skip { get; set; }
        public int take { get; set; }
        public Sort sorted { get; set; }
        public string[] group { get; set; }
        //Grid Action Params;
        public string action { get; set; }
        public string key { get; set; }
        public string keyColumn { get; set; }
        public string[] select { get; set; }
        public Search search { get; set; }
        public Where where { get; set; }
        public ApplicationUser value { get; set; }
    }

    public class Where
    {
        public bool isComplex { get; set; }
        public string field { get; set; }
        public string @operator { get; set; }
        public string @value { get; set; }
        public bool ignoreCase { get; set; }

    }
    public class Sort
    {
        public string name { get; set; }
        public string direction { get; set; }
     //   "sorted":[{"name":"Area","direction":"ascending"}],"group":["Area"]
    }

    public class Search
    {
        public string[] fields { get; set; }

        public string @operator { get; set; }

        public string key { get; set; }

        public bool ignoreCase { get; set; }
    }

控制器方法

 public async Task<ActionResult> DataSource(UserViewModel editParams)
   {

   }

1 个答案:

答案 0 :(得分:0)

您发送的JSON似乎与您的视图模型完全不匹配:

{
    "select": [
        "Area",
        "Id"
    ],
    "where": [
        {
            "isComplex": false,
            "field": "Area",
            "operator": "startswith",
            "value": "test",
            "ignoreCase": true
        }
    ],
    "sorted": [
        {
            "name": "Area",
            "direction": "ascending"
        }
    ]
}

考虑编写一个与此结构匹配的视图模型:

public class UserViewModel
{
    public string[] Select { get; set; }
    public Where[] where { get; set; }
    public Sorted[] sorted { get; set; }
}

public class Where
{
    public bool IsComplex { get; set; }
    public string Field { get; set; }
    public string Operator { get; set; }
    public string Value { get; set; }
    public bool IgnoreCase { get; set; }
}

public class Sorted
{
    public string Name { get; set; }
    public string Direction { get; set; }
}

现在您的控制器操作可以将此视图模型作为参数:

public async Task<ActionResult> DataSource(UserViewModel editParams)
{
    ...
}

我不熟悉您似乎正在使用的SyncFusion Asp.Net MVC grid,但您应该确保Content-Type: application/json请求HTTP标头与AJAX请求一起发送,以便ASP.NET MVC模型绑定器知道从客户端发送的内容类型。使用Web浏览器的开发人员工具栏或Fiddler等工具检查客户端发送的请求,并确保此标头存在。否则,视图模型将不受约束。