JQuery.Ajax()的data參數傳遞方式

 

最近,新學c# mvc,經過ajax post方式傳遞數據到controller。剛開始傳遞參數,controller中老是爲null。現記錄一下,可能不全,純粹記個學習日記。html

重點在於參數的方式,代碼爲例子前端

一、這裏  dataType: "json",表示返回的格式是jsonajax

前端: 
var saveAlbum = function () { $.ajax( { url: "/Home/PostAlbum", type: "POST", dataType: "json", data: { AlbumName: "shanghai", Entered: "5/9/2013" }, success: function (result) { alert(result); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); }
 controller: 

public ActionResult PostAlbum(test test) { string str = String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered); return Json(str);//--------對應請求中dataType: "json",表示須要返回json類型 //return String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered);//------若是是string,則會報錯 }

二、ajax請求中還要一個重要的參數: contentType: "application/json",表示傳入參數的格式json

 var saveAlbumJson = function () {
          
            $.ajax(
            {
                url: "/Home/PostAlbum",
                type: "POST",
                contentType: "application/json",
                dataType:"json",
                data: JSON.stringify({ "AlbumName": "shanghai", "Entered": "5/9/2013" }),
                success: function (result) {
                    alert(result);
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    alert(err);
                }
            });
        }
 [HttpPost]
        public ActionResult PostAlbum(test test)
        {
            string str = String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered);//傳入test實體
            return Json(str);
            //return String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered);
        }
 public class test
    {
        public string AlbumName { get; set; }
        public DateTime Entered { get; set; }
    }

三、若是要傳入list<實體>,好比List<test>,須要把傳入的data作轉換c#

   var saveAlbumJsonList = function () {
            $.ajax(
            {
                url: "/Home/AlbumList",
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify({"input":[{ AlbumName: "shanghai", Entered: "5/9/2013" },{...},{....}]}),
                success: function (result) {
                    alert(result);
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    alert(err);
                }
            });
        }
  public ActionResult PostAlbumList(List<test> input)//input必需要與data中數組中的key匹配
        {
            if (input != null)
            {
                string str = String.Format("保存成功PostAlbum:{0} {1:d}", input[0].AlbumName, input[0].Entered);
                return Json(str);
            }else
            {
                return Json("參數獲取錯誤!");
            }
            //return String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered);
        }

四、由上面三個例子,很容易想到,傳入多個list<實體>的方式數組

  function postEmployees() {
            $.ajax({
                type: "POST",
                url: "/Home/Employees",
                contentType: "application/json",
                dataType: "json",
                async: false,
                data: JSON.stringify({
                    "Employees": [{ "Id": "1", "lastName": "Gates" }, { "Id": "2", "lastName": "Bush" }, { "Id": "3", "lastName": "Carter" }],
                    "Employers": [{ "Id": "4", "lastName": "Gates" }, { "Id": "5", "lastName": "Bush" }, { "Id": "6", "lastName": "Carter" }]
                }),
                success: function (jsonResult) {
                    alert(jsonResult);
                }
            });
        }
  [HttpPost]
        public async Task<ActionResult> Employees(List<Employee> Employees, List<Employee> Employers)
        {
            return Json("Employees", JsonRequestBehavior.AllowGet);
        }
 public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }

        public string LastName { get; set; }
    }
相關文章
相關標籤/搜索