通過Ajax post Json類型的數據到Controller


 

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'}"。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM