jquery 给 action传递 json

来源:互联网 发布:php 评论加回复功能 编辑:程序博客网 时间:2024/06/05 21:30

假设 controller中的方法是如下:
public ActionResult ReadPerson(PersonModel model) 
        { 
            string s = model.ToString(); 
            return Content(s); 
        }
 
public ActionResult ReadPersons(List<PersonModel> model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }
 其中PersonModel定义如下:
public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }
 
        public int age 
        { 
            set; 
            get; 
        }
 
        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }
 
        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }
那么controller方法分别接受单个model和一个model的List。采用通过ajax传递参数。
对于传递单个参数的情况,假设js代码如下:
var person = { 
               id: "001", 
               name: "zhangsan", 
               age: "20", 
               gender: true, 
               city: "shanghai" 
           };
 
var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: person, 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);
 从chrome中截图可以看到如下:
传递的数据是一串Form数据,根据命名匹配的原则,也是可以取得数据的。
将option 的代码改成如下
var option = { 
               url: '/test/ReadPerson', 
               type: 'POST', 
               data: JSON.stringify(person), 
               dataType: 'html', 
               success: function (result) { alert(result); } 
           }; 
$.ajax(option);
其中JSON.stringify方法签名为 stringify ( value [ , replacer [ , space ] ] ),根据ECMA-262标准stringify 函数返回的是JSON格式的字符串。它可以有3个参数。摘抄如下:
The stringify function returns a String in JSON format representing an ECMAScript value. It can take three parameters. The first parameter is required. The value parameter is an ECMAScript value, which is usually an object or array, although it can also be a String, Boolean, Number or null. The optional replacer parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as a white list for selecting the object properties that will be stringified. The optional space parameter is a String or Number that allows the result to have white space injected into it to improve human readability.
默认的ContentType的属性值是"application/x-www-form-urlencoded"
 看请求头的截图:clipboard_thumb

因此,传递到controller的是一个json字符串,MVC根据命名匹配也是可以获得到参数的值。
将将option 的代码改成如下
var option = { 
                url: '/test/ReadPerson', 
                type: 'POST', 
                data: person, 
                dataType: 'html', 
                 contentType: 'application/json', 
                 success: function (result) { alert(result); } 
                }; 
把contentType改成json格式,那么得到的是出错的信息。
虽然person是json对象,但是jquery中的ajax,data会自动的被转换成查询字符串格式key1=value1&key2=value2这种形式,很显然这种形式不是json格式,因此会出错。
要避免转换成查询字符串格式,只需要设置processData为fasle即可。processData默认是true。
这里需要注意的是:当指定了contentType的时候,数据将不再按照Form Data的形式提交了,而是变成Request Data的形式提交。可以从图上的Request Header中看出。需要注意的是,Form Data提交的数据可以由FormCollection获得到。Request Data方式提交的则不能通过FormCollection获得。
如果把processData设置为默认值true。image_thumb[3]

如果把processData设置为false。image_thumb[2]

以上两种方式,按照application/json的类型传给都会失败,因为json是基于文本的格式,上面两种方式传递的都不是json文本。因此会出错。
因此,把option改成:
var option = { 
    url: '/test/ReadPerson', 
    type: 'POST', 
    data:JSON.stringify(person), 
    dataType: 'html', 
    contentType: 'application/json', 
    success: function (result) { alert(result); } 
}; 
则传递的就是json文本,因此根据命名匹配,就能获得值了。clipboard[8]_thumb

对于较为简单是数据类型,有时候不指定contentType也能通过命名匹配传值。但是对于稍微复杂点的数据类型,有时指定contentType: 'application/json',处理起来更加方便。
如果一个controller里的action方法是接受一个List类型的参数,比如:
public ActionResult ReadPersons(List<PersonModel> model)
那么js中先构造这样的一个json对象的数组。如下
var persons = [{
                id: "001",
                name: "zhangsan",
                age: "20",
                gender: true,
                city: "shanghai"
            },
            {
                id: "002",
                name: "lisi",
                age: "21",
                gender: false,
                city: "beijing"
            }
            ];
单纯一个数组传递是作为data传递是,Form Data也是无法识别出的。因此把这个数组再次组成一个json形式。如下:其中json的键值用model是为了能和controller中的参数名相同,可以匹配。
var jsonp = { model: persons };
           var option = {
               url: '/test/ReadPersons',
               type: 'POST',
               data: jsonp,
               dataType: 'html',
               success: function (result) { alert(result); }
           };
由于未指定contentType,因此是默认的application/x-www-form-urlencoded。此时是按照Form Data的方式传递的,

可以从截图中看到。但是这种格式的数据,controller中只能获得指定model用2个元素,无法获得元素中属性的值。


clipboard[1]如果把data改成JSON.stringify(jsonp),如下:    
var option = {
              url: '/test/ReadPersons',
              type: 'POST',
              data: JSON.stringify(jsonp),
              dataType: 'html',
              success: function (result) { alert(result); }
          }; 

那么传递过去的Form Data是一串字符串,controller跟无法识别出这个东西,因此获不到值。如果仅仅设置contentType: 'application/json',而传递的又不是json格式的数据,如下:
var option = {
    url: '/test/ReadPersons',
    type: 'POST',
    data: jsonp,
    dataType: 'html',
    contentType: 'application/json',
    success: function (result) { alert(result); }
};
因为jquery的ajax方法会把data转换成查询字符串,因此就变成如下的样子。这串文本当然不符合json格式,因此会出现下面的错误。


如果设置contentType: 'application/json',并且设置data: JSON.stringify(persons),如下:
var option = {
                url: '/test/ReadPersons',
                type: 'POST',
                data: JSON.stringify(persons),
                dataType: 'html',
                contentType: 'application/json',
                success: function (result) { alert(result); }
            };
那么可以获得到真正完整的json数据了clipboard[5]

最后,此处再演示一个更复杂的参数类型,以便加深理解。
首先看一下Controller中的方法签名,TestClassB 和一个TestClassA的List。稍显复杂。
public ActionResult Fortest(TestClassB TB,List<TestClassA> TA)
        {
            string result = "";
            return Content(result);
        }
再看TestClassA和TestClassB,更显复杂。但是结构要清晰的话,也不是很难。
public class TestClassA
    {
       public string a1 { set; get; }
       public List<string> a2 { set; get; }
    }
    public class TestClassB
    {
        public string b1 { set; get; }
        public InnerTestClassC ITCC { set; get; }
        public class InnerTestClassC
        {
            public List<int> c1 { set; get; }
        }
    } 看js代码:逐步的构造出一个json格式。
$("#btn").click(function () {
            var jsondata = { TB: {}, TA: [] };
            jsondata.TB.b1 = "b1";
            jsondata.TB.ITCC = {};
            jsondata.TB.ITCC.c1 = new Array(1, 2, 3, 4);
            var ta1 = {};
            ta1.a1 = "a1";
            ta1.a2 = new Array("a", "b", "x", "y");
           var ta2 = {};
            ta2.a1 = "a2";
            ta2.a2 = new Array("a2", "b2", "x2");
            jsondata.TA.push(ta1);
            jsondata.TA.push(ta2);
            var option = {
                url: '/test/Fortest',
                type: 'POST',
                data: JSON.stringify(jsondata),
                dataType: 'html',
                contentType: 'application/json',
                success: function (result) { alert(result); }
            };
            $.ajax(option);
        });
最终,发送出去的json字符串如下:
{"TB":{"b1":"b1","ITCC":{"c1":[1,2,3,4]}},"TA":[{"a1":"a1","a2":["a","b","x","y"]},{"a1":"a2","a2":["a2","b2","x2"]}]}
Controller接收到这个json串后,就能自动的匹配参数了。具体得到的参数如下截图:

 clipboard[6]clipboard[7]

原创粉丝点击