(.Net Core) ajax调用api方法

//-------------显示----------

$.ajax({
url: "https://localhost:44387/api/控制器名/方法名",
dataType: "json",
type: "get",
success: function (data) {
$.each(data, function (index, item) {
var tr = "<tr>" +
"<td>" + item.字段名+ "</td>" +
"<td>" + " <input type = 'button' value = '删除' onclick='Del(" + item.id + ")'/> " + "<input type = 'button' value = '编辑' onclick='Edit(" + item.id + ")'/> " + "</td>" +
"</tr>";
//添加到页面
$("#tb").append(tr);
});
}
});

//**************添加方法*********************

$.ajax({
url: "https://localhost:44387/api/控制器名/方法名",
data: obj,
dataType: "json",
accepts: "application/x-www-form-urlencoded",
contentType: "application/x-www-form-urlencoded",
type: "POST",
success: function (data) {
// console.log(data);

if (data> 0) {
alert("添加成功");
window.location.href = "Index";
}
else {

alert("添加失败");
}
}
});
});

//**///////////删除/////////////**//

function Del(id) {
if (confirm("确定删除?")) {
$.ajax({
url: "https://localhost:44387/api/控制器名/方法名",
data: { id: id },
dataType: "json",
type: "get",
success: function (data) {
if (data > 0) {
alert("删除成功");
window.location.reload();
}
}
});
}

return;
}

//+++++++++++++++修改+++++++++++

控制器中的方法

public IActionResult Edit(int ID)
{
ViewBag.Id = ID;
return View();
}

页面接受id

<input id="id" type="hidden" value="@ViewBag.Id"/>

//获取某条数据的信息进行反填
var id= $("#id").val()
$.ajax({
url: "https://localhost:44387/api/控制器名/方法名?Id="+id,
dataType: "json",
type: "Get",
success: function (data) {

//反填信息
$("#id名").val(data.##);
}
});
//保存修改后的信息
$("#btnSave").click(function () {

//获取修改后的页面信息
var obj = {};
obj.字段名=$("#id名").val();
$.ajax({
url: 'https://localhost:44387/api/控制器名/方法名',
data: obj,
dataType: "json",
accepts: "application/x-www-form-urlencoded",
contentType: "application/x-www-form-urlencoded",
type: "POST",
}).done(function (data) {


if (res > 0) {
alert("修改成功");

}
else {
alert("修改失败");

}
});

});

原文地址:https://www.cnblogs.com/xr0818/p/13072313.html