2018年7月6日 星期五

[ASP.NET] 使用AJAX讀取Controller回傳的JSON字串

後端Controller,使用JsonResult:

public class Student
{
   public int SN {get; set;}
   public string Name {get; set;}
}

[HttpPost]
public JsonResult GetStudent(int SN)
{
   List list = new List();
   list.add(new Student(){
      SN = 1,
   Name = "John",
   });
   list.add(new Student(){
      SN = 2,
   Name = "Bob",
   });
   list.add(new Student(){
      SN = 3,
   Name = "Tom",
   });
   
   var student = list.Where(x => x.SN == SN).FirstOrDefault();
   return Json(student);
}

後端Controller,使用ContentResult:

public class Student
{
   public int SN {get; set;}
   public string Name {get; set;}
}

[HttpPost]
public ContentResult GetStudent(int Sn)
{
   List list = new List();
   list.add(new Student()
   {
      SN = 1,
      Name = "John",
   });
   list.add(new Student()
   {
      SN = 2,
      Name = "Bob",
    });
   list.add(new Student()
   {
      SN = 3,
      Name = "Tom",
   });

   var student = list.Where(x => x.SN == SN).FirstOrDefault();
   string json = JsonConvert.SerializeObject(student);
   return Content(json, "application/json");
}

前端View的Javascript:

$.ajax({
    url: "@Url.Content("~/xxx/GetStudent")", //Controller的網址
    data: {
        SN: 2, //傳遞參數
    },
    type: "POST",
    dataType: 'json',
    success: function (data) {
        if ($.isEmptyObject(data)) {
            alert("查無資料");
        }
        else {
      alert(data.SN);
   alert(data.Name);
   alert(data.Sex);
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("發生錯誤!!");
        console.log(xhr.status);
        console.log(thrownError);
    }
});

沒有留言:

張貼留言