MVC中post集合或者实体对象的两种方法

集合
后台方法:
[HttpPost]
public bool SaveData(List<SelectListItem> list)
{
      return list != null && list.Count > 0;
}

//或者以下方式:
[HttpPost]
public async Task<bool> SaveData(SelectListItem[] list)
{
     return list != null && list.Length > 0;
}

 

 如果传入的参数为 

var tt = [
    { Selected: true, Text: "test1", Value: "1" },
    { Selected: false, Text: "test2", Value: "1" },
    { Selected: false, Text: "test3", Value: "1" }
];

 

方法一:(成功)
$.post("http://localhost:9011/Home/SaveData", { list : tt }, function (arr) {
    alert(arr);  //结果为true
});

 

方法二:(成功)
$.ajax({
   type: "post",
   url: "http://localhost:9011/Home/SaveData",
   contentType: "application/json",
   data: JSON.stringify(tt),
   success: function (arr) {
      alert(arr); //结果为true
   }
});

 

 
单对象
后台方法:
[HttpPost]
public bool SaveData2(SelectListItem item)
{
    return item != null && string.IsNullOrEmpty(item.Text) == false;
}

如果传入的参数为 

var tt = { Selected: true, Text: "test1", Value: "1" };

方法一:(成功)

$.post("http://localhost:9011/Home/SaveData2", tt, function (arr) {
    alert(arr);  //结果为true
});
方法二:(成功)
$.ajax({
   type: "post",
   url: "http://localhost:9011/Home/SaveData2",
   contentType: "application/json",
   data: JSON.stringify(tt),
   success: function (arr) {
      alert(arr); //结果为true
   }
});

 

posted @ 2017-04-14 16:45  hejiyong  阅读(2283)  评论(0编辑  收藏  举报