通过Ajax post Json类型的数据到Controller

本文详细介绍了如何使用Ajax的POST方法发送JSON格式的数据到ASP.NET MVC Controller,并解析了在Controller端如何接收和处理这些数据。同时,文章强调了contentType参数的重要性,以及正确使用JSON.stringify方法来确保数据能被正确传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function getVehiclesPreLocation(dataArray) {

var arr = new Array();
        for (var i = 0; i < dataArray.length; i++) {
            arr.push(JSON.parse(dataArray[i]).No);
        }
        var dataSend = JSON.stringify({ "data": '' + JSON.stringify(arr) + '' });//此处的”data”即为action的入参名

        $.ajax({
            type: "POST",
            url: "/控制器类名/Action方法名",
            contentType: "application/json",//必须有
            dataType: "json", //表示返回值类型,不必须
            data: dataSend,//相当于 //data: "{'str1':'foovalue', 'str2':'barvalue'}",
            success: function (jsonResult) {
             
                //获取数据ok
                alert(jsonResult);
            }
        });

};

 

       [HttpPost]
       public ActionResult GetMyData(string data)
       {
           if (string.IsNullOrEmpty(data)) return null;

           var noList = JsonConvert.DeserializeObject<List<string>>(data);
           string jsonString = _srv.GetData(noList);

           return Json(jsonString);
       }

-----------------------------------------------------------------------------------

View

复制代码
    function postSimpleData() {
        $.ajax({
            type: "POST",
            url: "/Service/SimpleData",
            contentType: "application/json", //必须有
            dataType: "json", //表示返回值类型,不必须
            data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' }),  //相当于 //data: "{'str1':'foovalue', 'str2':'barvalue'}",
            success: function (jsonResult) {
                alert(jsonResult);
            }
        });
    }
    function postListString() {
        $.ajax({
            type: "POST",
            url: "/Service/ListString",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({ "BuIds": ["1", "2", "3"] }),
            success: function (jsonResult) {
                alert(jsonResult);
            }
        });
    }
    function postEmployees() {
        $.ajax({
            type: "POST",
            url: "/Service/Employees",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                "Employees": [
                                    { "firstName": "Bill", "lastName": "Gates" },
                                    { "firstName": "George", "lastName": "Bush" },
                                    { "firstName": "Thomas", "lastName": "Carter" }
                                 ]

            }),
            success: function (jsonResult) {
                alert(jsonResult);
            }
        });
    }
复制代码

 

Controller

复制代码
        [HttpPost]
        public ActionResult SimpleData(string foo, string bar)
        {
            return Json("SimpleData", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult ListString(List<string> buIds)
        {
            return Json("ListString", JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult Employees(List<Employee> Employees)
        {
            return Json("Employees", JsonRequestBehavior.AllowGet);
        }
复制代码
复制代码
    public class Employee
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }
    }
复制代码

 

结果

 

值得注意的有2点:

1)Ajax 选项中

 contentType: "application/json"

这一条必须写,表明request的数据类型是json。

dataType: "json"  

这一条表示返回值的类型,不必须,且依据返回值类型而定。

2)选项中

data: JSON.stringify({ 'foo': 'foovalue', 'bar': 'barvalue' })  

很多时候我们将数据写作:

{ 'foo': 'foovalue', 'bar': 'barvalue' }

这样会导致错误,因为js会默认将这个json对象放到表单数据中,故而导致controller接收不到。

有两种办法处理:第一种方式是用JSON.stringify()函数,其中JSON被Ecmascript5定义为全局对象。有关该函数的用法,见此处

                    第二种方式是直接用双引号包裹起来,比如data: "{'str1':'foovalue', 'str2':'barvalue'}"。

 

posted on 2015-06-05 16:06  v.e.n.u.s 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jx270/p/4554875.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值