• asp.net MVC 使用JQuery.Ajax


    使用到:Jquery.js 以及 Newtonsoft.Json.dll

    客户端调用方式:

    $("#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
    }
    }

    转载原文:http://blog.163.com/china__xuhua/blog/static/1997231692011101842121717/

  • 相关阅读:
    void型指针转换。
    MSSQL数据库中记录生日与输入的年龄,进行比对
    [转][C#]内置的 DateTime 用法
    Asp.Net 文件操作基类(读取,删除,批量拷贝,删除,写入,获取文件夹大小,文件属性,遍历目录)
    点击Repeater中的按钮,获取Repeater中TextBox中的值
    [转]UrlReWriter 使用经验小结收藏
    C#中实现VB.net中ReDim功能
    在存储过程中循环表中的记录集
    ADO.net取存储过程的返回值以及存储过程中Return和OUTPUT的区别
    部分FCKeditor常用JS函数
  • 原文地址:https://www.cnblogs.com/lizihong/p/4297832.html
Copyright © 2020-2023  润新知