ASP.NET MVC 传递 JSON数据到后台

刚刚帮朋友的忙,传递JSON数据到后台,将代码贴到这里,当个记录吧

 

  1. 下载 NewtonSoft.Json
  2. 将NewtonSoft.Json.dll 引入程序中
  3. 现在开始看一下前台数据:
  4. function Test() {
            var data = [
                         { Id: 1, Name: "Test" },
                         { Id: 2, Name: "Test2" }
                     ];
                         alert(String.toSerialize(data));
            $.post("/Home/Test/", { users: String.toSerialize(data) }, function (text) {
                alert(String.toSerialize(text));
            }, "json");
        }

        String.toSerialize = function (obj) {
            var ransferCharForJavascript = function(s) {
                var newStr = s.replace(
                    /[\x26\x27\x3C\x3E\x0D\x0A\x22\x2C\x5C\x00]/g ,
                    function(c) {
                        var ascii = c.charCodeAt(0);
                        return '\\u00' + (ascii < 16 ? '0' + ascii.toString(16) : ascii.toString(16))
                    }
                );
                return newStr;
            };
            if (obj == null) {
                return null;
            } else if (obj.constructor == Array) {
                var builder = [];
                builder.push("[");
                for (var index in obj) {
                    if (typeof obj[index] == "function") continue;
                    if (index > 0) builder.push(",");
                    builder.push(String.toSerialize(obj[index]));
                }
                builder.push("]");
                return builder.join("");
            } else if (obj.constructor == Object) {
                var builder = [];
                builder.push("{");
                var index = 0;
                for (var key in obj) {
                    if (typeof obj[key] == "function") continue;
                    if (index > 0) builder.push(",");
                    builder.push("\"{0}\":{1}".format( key, String.toSerialize(obj[key])));
                    index++;
                }
                builder.push("}");
                return builder.join("");
            } else if (obj.constructor == Boolean) {
                return obj.toString();
            } else if (obj.constructor == Number) {
                return obj.toString();
            } else if (obj.constructor == String) {
                return '"{0}"'.format(ransferCharForJavascript(obj));
            } else if (obj.constructor == Date) {
                return '{"__DataType":"Date","__thisue":{0}}'.format(obj.getTime() - (new Date(1970, 0, 1, 0, 0, 0)).getTime());
            } else if (this.toString != undefined) {
                return String.toSerialize(obj);
            }
        };

        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != 'undefined'
          ? args[number]
          : match;
            });
        };
  5. 前台可以调用js方法传递到后台
  6. 后台Model添加JsonBinder处理类 JsonBinder.cs
  7. /// <summary>
        
    /// Json数据绑定类
        
    /// </summary>
        
    /// <typeparam name="T"></typeparam>
        public class JsonBinder<T> : IModelBinder
        {

            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                //从请求中获取提交的参数数据
                var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;
                //提交参数是对象
                if (json.StartsWith("{") && json.EndsWith("}"))
                {
                    JObject jsonBody = JObject.Parse(json);
                    JsonSerializer js = new JsonSerializer();
                    object obj = js.Deserialize(jsonBody.CreateReader(), typeof(T));
                    return obj;
                }
                //提交参数是数组
                if (json.StartsWith("[") && json.EndsWith("]"))
                {
                    IList<T> list = new List<T>();
                    JArray jsonRsp = JArray.Parse(json);

                    if (jsonRsp != null)
                    {
                        for (int i = 0; i < jsonRsp.Count; i++)
                        {
                            JsonSerializer js = new JsonSerializer();
                            object obj = js.Deserialize(jsonRsp[i].CreateReader(), typeof(T));
                            list.Add((T)obj);
                        }
                    }
                    return list;
                }
                return null;
            }
  8. Student实体类
  9. [JsonObject]
        public class Student
        {
            [JsonProperty("Id")]
            public int Id { getset; }
            [JsonProperty("Name")]
            public string Name { getset; }
        }
  10. Controller 中的 Action处理
  11. [HttpPost]
            public string Test([ModelBinder(typeof(JsonBinder<Student>))]List<Student> users)
            {
                if(users.Count == 2)
                    return "true";
                return "false";
            }

 

posted on 2012-06-20 19:35  小二黑  阅读(764)  评论(0编辑  收藏  举报

导航