jQuery Ajax pass JavaScript Object and Array to ASP.net MVC Controller
前言
假設在Controller裡有這樣的程式碼↓
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1TestAjaxPassObject.Controllers
{
/// <summary>
/// 自訂類別
/// </summary>
public class Person
{
public string Name { get; set; }
}
public class HomeController : Controller
{
//顯示畫面用
public ActionResult Index()
{
return View();
}
//給Ajax呼叫用
[HttpPost]
public ActionResult GetData(int ID,Person person,List<Person> persons)
{
StringBuilder sb = new StringBuilder();
if (persons!=null && persons.Count>0)
{
foreach (Person obj in persons)
{
sb.Append(obj.Name + ",");
}
}
return Content($"ID:{ID},person.Name:{person.Name},persons.Count:{persons.Count},persons.Names:{sb.ToString()}");
}
}
}
實作
如果想透過jQuery Ajax傳遞JavaScript Object 或Array到Controller裡的Action可以正常接收資料的話↓
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Demo</title>
</head>
<body>
<!--引用jQuery核心-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script type="text/javascript">
$(function () {
//建立物件
let person = { Name: "Jack" };
//建立陣列
let persons = new Array();
persons.push({ Name: "Apple" });
persons.push({ Name: "Banana" });
//ajax request
let promise =
$.ajax({
url: "@Url.Action("GetData","Home")",
method: "post",
contentType: 'application/json',
data: JSON.stringify({ ID: 1, person: person, persons: persons })
});
promise.done(function (data)
{
//顯示Server端回傳的資料
console.log(data);
});
});
</script>
</body>
</html>
需留意以下三個值必填,method絕不可用"GET"
method: "post",
contentType: 'application/json',
data: JSON.stringify({ ID: 1, person: person, persons: persons })
以上是ASP.net MVC各版本通用寫法
如果專案為ASP.net MVC 5以上版本的話
jQuery Ajax寫法可以更簡潔↓(我想微軟應該有改寫過ModelBinder吧)
//ajax request
let promise = $.ajax({
url: "@Url.Action("GetData","Home")",
method: "post",
data: { ID:1, person: person, persons: persons }
});
※上述method也絕不可用"GET"