我在嘗試按 ID 洗掉一行時遇到問題。我在表格中顯示我的資料庫的每一行,在每一行旁邊我都有一個按鈕,用于洗掉資料庫中的特定行。
它應該只洗掉具有該特定 ID 的行,但實際發生的是,我什至沒有按下按鈕,但是當訪問頁面時 - 資料庫的全部內容被洗掉。
我做錯什么了?
到目前為止,這是我的代碼:
控制器:
public class AdminController : BaseController
{
private UserContext context;
public AdminController()
{
context = new UserContext();
}
public void delete_by_id(int id)
{
context.Users.Where(x => x.Id == id).DeleteFromQuery();
}
// GET: Admin
[AdminMod]
public ActionResult Index()
{
SessionStatus();
if ((string)System.Web.HttpContext.Current.Session["LoginStatus"] != "login")
{
return RedirectToAction("Index", "Login");
}
var user = System.Web.HttpContext.Current.GetMySessionObject();
UserData u = new UserData
{
Username = user.Username,
Level = user.Level,
};
return View("Index", u);
}
}
用戶背景關系:
public class UserContext : DbContext
{
public UserContext() :
base("name=WebApplication1")
{
}
public virtual DbSet<UDbTable> Users { get; set; }
}
索引.cshtml:
@using WebApplication1.Controllers
@using WebApplication1.Domain.Enums
@using WebApplication1.Extension
@using WebMatrix.Data
@{
ViewBag.Title = "Admin";
Layout = "~/Views/Shared/_Layout.cshtml";
var db = Database.Open("WebApplication1");
var selectQueryString = "SELECT * FROM UDbTables ORDER BY Id";
}
<script>
function refreshPage() {
window.location.reload();
}
</script>
<div class="container" style="margin-top: 1%;">
<h1>AdminPage</h1>
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">#Id</th>
<th scope="col">Username</th>
<th scope="col">Email</th>
<th scope="col">Level</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in db.Query(selectQueryString))
{
<tr>
<th scope="row">#@row.Id</th>
<td>@row.Username</td>
<td>@row.Email</td>
@{
if (@row.Level == 0)
{
<td>User</td>
}
else if (row.Level == 1)
{
<td>Premium</td>
}
else
{
<td>Admin</td>
}
}
<td>
<button type="button" data-bs-togle="modal" data-bs-target="#IdModal" class="btn btn-danger" data-toggle="tooltip" data-placement="right" title="Delete User" id="@row.Id" onclick ="refreshPage()">
@{
var smth = new AdminController();
smth.delete_by_id(row.Id); //HERE IS WHERE I CALL THE QUERY
}
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
在這里,我有證據證明為每一行分配了正確的 ID:

uj5u.com熱心網友回復:
創建用于提交洗掉操作的 POST 請求的表單。
<td>
@using (Html.BeginForm("Delete", "Admin", new { id = row.Id }, FormMethod.Post))
{
<button type="submit" data-bs-togle="modal" data-bs-target="#IdModal" class="btn btn-danger" data-toggle="tooltip" data-placement="right" title="Delete User" id="@row.Id">
<i class="fas fa-trash"></i>
</button>
}
</td>
在AdminController中,你需要一個 Delete with[HttpPost]方法來執行洗掉操作,然后回傳 View。
public class AdminController : BaseController
{
...
[HttpPost]
public ActionResult Delete(int id)
{
delete_by_id(id);
// Return desired view
return Index();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471023.html
