[英]Refreshing Page After Delete With Ajax in ASP.NET MVC
从数据库中删除记录后,我正在尝试刷新页面。 I managed to hack the behaviour I want by reloading the windows inside the ajax 'error' but I'm not quite sure why I can't return success to ajax from my controller.
我已经尝试了以下操作:controller(REDIRECTTOROUTE,REDIRECTTOACTION(“ index”)中的不同返回类型(rectire(return ok(return Ok()),加上邮寄和ZA34A66659BCEAE779F2285E7779F27185E.7779F27185EBCAER ERASE(return Ok())
我所做的一切(除了在错误块内重新加载)都从数据库中删除了记录,但从不使用新表刷新页面。
看法:
@model todo.ViewModels.TodoViewModel
<table>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
@foreach (var t in Model.TodoList)
{
<tr>
<td>@t.Id</td>
<td>@t.Name</td>
<td><input type="submit" class="btn btn-danger" value="Delete" onClick="deleteTodo(@t.Id)" /></td>
</tr>
}
</table>
js:
function deleteTodo(i)
{
$.ajax({
url: 'Todo/Delete',
type: 'GET',
dataType: 'json',
data: {
id: i
},
success: function() {
alert('success');
},
error: function() {
alert('fail');
window.location.reload();
}
});
}
Controller
public IActionResult Index()
{
var tdlvm = GetAllTodos();
return View(tdlvm);
}
[HttpGet]
public RedirectToActionResult Delete(int id)
{
using (var connection =
new SqlConnection("Server=(localdb)\\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Todo"))
{
using (var tableCmd = connection.CreateCommand())
{
connection.Open();
tableCmd.CommandText = $"DELETE from todo WHERE Id = '{id}'";
int rowCount = tableCmd.ExecuteNonQuery();
}
}
return RedirectToAction("Index");
}
internal TodoViewModel GetAllTodos()
{
List<Todo> todoList = new();
当您使用 ajax 重定向时,controller 操作不起作用。 尝试这个
success: function() {
alert('success');
window.location.href= "/home/index";
},
您正在尝试从Controller
重定向,这并不是最好使用AJAX
完成的。 AJAX
用于更新页面的一部分,一般不用于重定向到其他页面。 在您的情况下,您可以执行以下操作:
您需要将JsonResult
从您的Controller
返回到您的AJAX
:
[HttpGet]
public JsonResult Delete(int id)
{
int rowCount=0;
using (var connection =
new SqlConnection("Server=(localdb)\\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Todo"))
{
using (var tableCmd = connection.CreateCommand())
{
connection.Open();
tableCmd.CommandText = $"DELETE from todo WHERE Id = '{id}'";
rowCount = tableCmd.ExecuteNonQuery();
}
}
if(rowCount > 1)
{
return Json(new {status="true", msg= "Successfully deleted"}, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new {status="false", msg= "Could not delete"}, JsonRequestBehavior.AllowGet);
}
}
您可以像这样在AJAX
中处理这个问题:
function deleteTodo(i)
{
$.ajax({
url: 'Todo/Delete',
type: 'GET',
dataType: 'json',
data: {
id: i
},
success: function(data) {
if(data.status=="true")
{
var urlToRedirect= '@Url.Action("Index","Home")';
window.location.href = urlToRedirect; //Redirect here
}
else if(data.status=="false")
{
alert(data.msg)
}
},
error: function() {
alert('fail');
window.location.reload();
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.