MVC + JQUERY + AJAX的几种方式

// 传过去一个简单值,获取一个简单值
$.ajax({  
         type: "GET",
         url: '<%= Url.Action("xx", "Corp") %>', 
         data: "type=11",
         success: function (msg) { alert(msg); }  
       }); 
public string xx()
{
    string s = this.Request.QueryString["type"];
    return s + ":ssssss";
}
// 获取一个复杂值
 $.ajax({
        url: '<%= Url.Action("xx", "Corp") %>',
        type: "POST",
        success: function(data) {
            var obj = eval("(" + data + ")");
            alert(obj.name);
        }
    }); 
// 这样更方便。
 $.ajax({
        url: '<%= Url.Action("xx", "Corp") %>',
        type: "POST",
        dataType:"json",               
        success: function(data) {
            alert(data.name);
        }
    });

public ActionResult xx()
{
    return this.Json( new
    {
        name = "Dr.Worm",
        worm = "Programer"
    } );
}
 
// 传过去一个复杂值,获取一个复杂值
$.ajax({
    url: '<%= Url.Action("xx", "Corp") %>',
    type: "POST",
    dataType: "json",
    data: "ID=1&FirstName=C&LastName=HY",
    success: function(data) {
        alert(data.ID + data.FirstName + data.LastName);
    }
}); 
 
public JsonResult xx( FormCollection form )
{
    return Json( new
    {
        ID = int.Parse(this.Request.Form[ "ID" ] ),
        FirstName = "w:" + this.Request.Form[ "FirstName" ],
        LastName = "s:" + this.Request.Form[ "LastName" ]
    } );
}
客户端调用方式:
$("#ButAjax").click(function() {
        $.ajax({
            type: "POST",  //默认是GET
            url: "/AjaxTest/getPerson",
            data: "ID=1&FirstName=C&LastName=HY",
            async: true,  //异步
            cache: false, //不加载缓存
            success: function(obj) {
                alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
            },
            error: function() {
                alert("请求失败");
            }
        });
    });
 
    $("#ButAjax2").click(function() {
        $.ajax({
            type: "POST",  //默认是GET
            url: "/AjaxTest/getPerson2?ID=3&FirstName=C&LastName=HY",
            async: true,  //异步
            cache: false, //不加载缓存
            success: function(obj) {
                alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
            },
            error: function() {
                alert("请求失败");
            }
        });
    });
 
    $("#ButAjax3").click(function() {
        $.ajax({
            type: "POST",  //默认是GET
            url: "/AjaxTest/getString",
            async: true,  //异步
            cache: false, //不加载缓存
            success: function(str) {
                alert(str);
            },
            error: function() {
                alert("请求失败");
            }
        });
    });
 
    $("#ButAjax4").click(function() {
        $.ajax({
            type: "POST",  //默认是GET
            url: "/AjaxTest/getJsonString",
            async: true,  //异步
            cache: false, //不加载缓存
            success: function(str) {
                var obj = eval(str);
                $.each(obj, function(item, value) {
                    alert(item + ":" + obj[item]);
                });
            },
            error: function() {
                alert("请求失败");
            }
        });
    });
 
        //================================================================
 
        $("#ButJson1").click(function() {
            $.getJSON("/AjaxTest/getJson1", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });
 
        $("#ButJson2").click(function() {
            $.getJSON("/AjaxTest/getJson2", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });
 
        $("#ButJson3").click(function() {
            $.getJSON("/AjaxTest/getJson3", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });
 
        $("#ButJson4").click(function() {
            $.getJSON("/AjaxTest/getJsonSerializingJson", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });
 
        $("#ButJson5").click(function() {
           
$.getJSON("/AjaxTest/getJsonDeSerializingJson", { json:
'{"ID":201,"FirstName":"C","LastName":"HY","Man":true}' },
function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });
 
 
 
        //================================================================
 
        $("#ButSerializing").click(function() {
            $.ajax({
                type: "POST",
                url: "/AjaxTest/testSerializingJson",
                data: "ID=101&FirstName=C&LastName=HY&Man=false",
                async: true,
                cache: false,
                success: function(obj) {
                    alert(obj);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });
 
        $("#ButDeSerializing").click(function() {
            $.ajax({
                type: "POST",
                url: "/AjaxTest/testDeSerializingJson",
                data: 'json={"ID":201,"FirstName":"C","LastName":"HY","Man":true}',
                async: true,
                cache: false,
                success: function(obj) {
                    alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });
 
        $("#ButSerializingList").click(function() {
            $.ajax({
                type: "POST",
                url: "/AjaxTest/serializingList",
                data: "",
                async: true,
                cache: false,
                success: function(obj) {
                    alert(obj + "length:" + obj.length);
                    $.each(obj, function() {
                        $.each(this, function(item, value) {
                            alert(item + ":" + json[item]);
                        });
                    });
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });
 
--------------------------------------------------------------------------------
 
Controllers 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Mvc;
 
namespace MvcApplication.Controllers
{
    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Man { get; set; }
    }
    public class AjaxTestController : Controller
    {      
        #region  ===============$.Ajax测试=================
        /// <summary>
        /// 测试返回对象
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public JsonResult getPerson(FormCollection form)
        {
            Person p = new Person
            {
                ID = int.Parse(form["ID"]),
                FirstName = form["FirstName"],
                LastName = form["LastName"]
            };
            return Json(p);
        }
 
        /// <summary>
        /// 经测试发现:当Global中定义{controller}/{action}/{id}时
        /// 前台url?ID=3&FirstName=C&LastName=HY传到后台时ID值为""
        /// 所以把Global中定义为{controller}/{action}/{uid}
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public JsonResult getPerson2(string ID, string FirstName, string LastName)
        {
            Person p = new Person
            {
                ID = int.Parse(ID),
                FirstName = FirstName,
                LastName = LastName
            };
            return Json(p);
        }
 
        /// <summary>
        /// 测试返回字符串
        /// </summary>
        /// <returns></returns>
        public ContentResult getString()
        {
            return Content("{id:'2',FirstName:'C',LastName:'HY'}");
        }
 
        /// <summary>
        /// 测试返回json字符串
        /// </summary>
        /// <returns></returns>
        public ContentResult getJsonString()
        {
            return Content("({id:'2',FirstName:'C',LastName:'HY'})");
        }
 
        #endregion
 
        #region ==============$.getJSON(返回json格式测试)============
 
        /// <summary>
        /// 经测试发现必须是双引号(")不能是单引号(')
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJson1(string ID, string FirstName, string LastName)
        {
            return Content("{/"id/":1,/"name/":/"chy/",/"flag/":true}");
        }
 
        /// <summary>
        /// 经测试发现必须是双引号(")不能是单引号(')
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJson2(string ID, string FirstName, string LastName)
        {
            return Content("{/"id/":/"2/",/"name/":/"chy/"}");
        }
 
        /// <summary>
        /// 经测试发现必须是双引号(")不能是单引号(')
        /// 产生错误前台没反应
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJson3(string ID, string FirstName, string LastName)
        {
            return Content("{'id':'3'}");
        }
 
        #endregion
 
        #region============Newtonsoft.Json.dll(json序列化和反序列化测试)=============
 
        /// <summary>
        /// $.Ajax序列化Json
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult testSerializingJson(FormCollection form)
        {
            Person p = new Person
            {
                ID = int.Parse(form["ID"]),
                FirstName = form["FirstName"],
                LastName = form["LastName"]
            };
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
        }

/// <summary>
        /// $.Ajax反序列化json
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public JsonResult testDeSerializingJson(FormCollection form)
        {
            Person p = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(form["json"].ToString());
            return Json(p);
        }
 
        /// <summary>
        /// $.getJSON序列化Json
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJsonSerializingJson(string ID, string FirstName, string LastName)
        {
            Person p = new Person
            {
                ID = int.Parse(ID),
                FirstName = FirstName,
                LastName = LastName
            };
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
        }
 
        /// <summary>
        /// $.getJSON反序列化json
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public ContentResult getJsonDeSerializingJson(string json)
        {
            Person p = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
        }
 
        #endregion
 
        #region================返回集合================
 
        public JsonResult serializingList()
        {
            List<Person> ls = new List<Person>();
            ls.Add(new Person
            {
                ID = 1,
                FirstName = "C",
                LastName = "HY",
                Man = false
            });
 
            ls.Add(new Person
            {
                ID = 2,
                FirstName = "Z",
                LastName = "JJ",
                Man = true
            });
            return Json(ls);
        }
 
        public JsonResult deSerializingList(string json)
        {
            List<Person> listP = new List<Person>();
 
            List<string> listStr = json.Split(',').ToList<string>();
 
            foreach (string s in listStr)
            {
                listP.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(s));
            }
 
            return Json(listP);
        }
 
        #endregion
    }
}

最新文章

  1. JavaScript获取浏览器高度和宽度值(documentElement,clientHeight,offsetHeight,scrollHeight,scrollTop,offsetParent,offsetY,innerHeight)
  2. 20140701立项 移植WatermarkLabelSys
  3. Java基础复习笔记系列 七 IO操作
  4. 基于jPlayer的三分屏制作
  5. linux 下第一个cordova android app
  6. Windows Live Writer技巧
  7. java判断list为空
  8. JavaScript的IIFE(即时执行方法)
  9. Optimizing shaper — hashing filters (HTB)
  10. VHD_Update_diskpart
  11. 和阿文一起学H5--设计稿尺寸全攻略
  12. object-c实现的 在PHP中oauth加密算法
  13. SCU 4440 Rectangle 2015年四川省赛题
  14. ASP.net获取当前页面的文件名,参数,域名等方法
  15. mysql alter example
  16. IT第四天 - 运算符、随机数、Math类
  17. Swift - 设置网格UICollectionView的单元格间距
  18. (原创)Python 自动化测试框架详解
  19. 使用SQL 提示优化sql
  20. bzoj 4710: [Jsoi2011]分特产

热门文章

  1. hi3531的h264压缩中改动波特率
  2. css匹配原理与优化
  3. NotificationListenerService不能监听到通知
  4. Android App用MulticastSocket监听组播,为什么连接到不同路由、在不同手机上跑,有的能收到有的收不到
  5. C#基础篇01
  6. [整理]:oracle spool 用法
  7. photoshop 常用快捷键大全
  8. android测试分析1
  9. asp.net mvc Remote远程验证
  10. 学习笔记_Java_day12_Cookie