1、ajax 請求
$.post()是jquery一個簡單的 POST 請求功能以取代復雜 $.ajax .
參數:
url,[data],[callback],[type]
url:發送請求地址。
data:待發送 Key/value 參數。
callback:發送成功時回調函數。
type:返回內容格式,xml, html, script, json, text, _default。
model: data.field 這里 model為后台參數名 data.field 為實體對應 可以是 List
$.post("/Admin/User/UserAdd", {model: data.field }, function (data) { alert(JSON.stringify(data)); });
$.ajax jq的標准ajax請求 data 就是一個json對象
注意 contentType 為 application/x-www-form-urlencoded; charset=UTF-8 或者 application/json;charset=utf-8 否則后台接收不到 具體用哪個自己試吧
$.ajax({
type: "post",
url: "/Admin/User/UserAdd",
dataType: "json",
data: data.field,
contentType: 'application/json;charset=utf-8',//向后台傳送格式
success: function (data) {
if (data.success) {
$("searchResult").html(data.msg);
} else {
$("#searchResult").html("出現錯誤:" + data.msg);
}
},
error: function (jqXHR) {
aler("發生錯誤:" + jqXHR.status);
}
});
C# MVC 后台接收
方法一:通過Request.Form
[HttpPost] public ActionResult Test() { string id=Request.Form["id"]; return View(); }
方法二:通過映射到控制器方法參數
[HttpPost] public ActionResult Test(string id) { //id是獲取來自View表單POST過來的控件名為id的值 return View(); }
方法三:通過映射到視圖數據對象
[HttpPost] public ActionResult Test(TModel model) { string id = model.id; return View(); }
[HttpPost] public ActionResult Test(List<TModel> model) { string id = model.id; return View(); }