关闭

MVC Controller 返回JSON数组

标签: MVCJSON数组
2047人阅读 评论(0) 收藏 举报
分类:
1、 Controller后台:

        [AcceptVerbs(HttpVerbs.Post)]
        /// <summary>
        /// (Json返回列表字符串)
        /// </summary>
        /// <returns></returns>
        public ContentResult SelectStudentListByName(string studentName)
        {
            string studentName = Server.UrlDecode(Request["StudentName"]);
            ContentResult result = new ContentResult();
            List<StudentInfo> staffList = Utility.SelectStudentListByName(studentName);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            result.Content = serializer.Serialize(staffList);
            return result;
        }

      2、前台JS操作:

        $.post('/Student/SelectStudentListByName/', { StudentName: escape($("#StudentName").val()) }, function(data) {//使用Jquery的post方式异步访问Controller:Student    Action:SelectStudentListByName 并返回json数组格式字符串
            var studentNameList = '';
            var studentList = eval(data);//将json格式字符串用eval转换成JS对象,转换后可遍历后直接访问json元素
            if (studentList.length > 0) {
                //遍历json数组获取每个学生对象
                $(studentList).each(function(i) {
                    //json数组格式:[{StudentID:1;StudentName:张三;Age:18},{StudentID:2;StudentName:李四;Age:19},{StudentID:3;StudentName:王五;Age:20}]
                    var student = StaffList[i];
                    var studentID = student.StudentID;
                    var studentName = student.StudentName;
                    var age = student.Age;
                });              
            }
        });

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:189034次
    • 积分:3103
    • 等级:
    • 排名:第11168名
    • 原创:109篇
    • 转载:94篇
    • 译文:0篇
    • 评论:28条
    最新评论