【发布时间】:2020-06-11 04:05:45
【问题描述】:
我正在使用 api 在 .net core mvc 项目中执行 CRUD 操作,并使用 List 来存储所有数据而不是数据库。我想使用 jquery 和 ajax 直接从我的 html 页面调用 api。但现在我被卡住了使用编辑操作(这是一种 POST 方法)。在编辑页面中,当我单击“保存”按钮时,它只是刷新页面,没有任何反应。
这是视图页面中用于编辑的jquery,Ajax gievn
@section Scripts{
<script>
var id = localStorage.getItem("empid");
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44347/api/Values/Edit/" + id,
success: function (data) {
$('#id').val(data.id)
$('#fname').val(data.fname)
$('#lname').val(data.lname)
$('#location').val(data.location)
$('#contact').val(data.contact)
$('#email').val(data.email)
$('#password').val(data.password)
$('#roles').val(data.roles)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("alertt");
$("#postResult").val(jqXHR.statusText);
}
});
$('#save').click(function () {
var obj = {};
obj.id = $('#id').val();
obj.fname = $('#fname').val();
obj.lname = $('#lname').val();
obj.location = $('#location').val();
obj.contact = $('#contact').val();
obj.email = $('#email').val();
obj.password = $('#password').val();
obj.roles = $('#roles').val();
$.ajax({
type: "POST",
url: "https://localhost:44347/api/Values/Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
success: function (data) {
window.location.href = "/Home/Details/";
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error occured");
$("#postResult").val(jqXHR.statusText);
}
});
});
</script>
}
这是在编辑页面点击保存按钮时调用的api函数
[HttpPost("Save")]
public IActionResult Save(StudentModel student)
{
obj1 = new StudentModel();
obj1 = obj2.Save(student);
if (obj1 != null)
{
return Ok(obj1);
}
return null;
}
【问题讨论】:
-
它只是刷新页面,什么也没有发生 - 通常发生在您有一个表单并认为仅将 javascript 添加到单击/提交操作不会执行常规表单提交时...您需要prevent default event 处理 .... 即
$('#save').click(function (e) { e.perventDefault(); rest of your code- 或添加$('form').submit(function(e) { e.perventDefault();}
标签: javascript jquery asp.net-core-mvc asp.net-ajax asp.net-core-webapi