删除并更新 MVC5 中的 SQL 表
本文关键字:SQL 中的 MVC5 更新 删除 | 更新日期: 2023-09-27 18:37:23
我正在使用MVC5。 我在 Index.cshtml 中有一个 SQL 数据工作表。
我有一个简单的SQL表,由五个元素组成,testID是主键,没有错误。
我在这里尝试做的是删除一行数据并让它更新 SQL 表。
Index.cshtml
<center>
<table>
<tr><td colspan="5" align="center"><br /><br /><h1>Table1 Printout</h1></td></tr>
<tr><td align="center">testID</td><td align="center">datetime</td><td align="center">col1</td><td align="center">col2</td><td align="center">col3</td><td></td></tr>
@foreach (var item in Model.thistable)
{
<tr><td>@item.testID</td><td>@item.datetime</td><td>@item.col1</td><td>@item.col2</td><td>@item.col3</td><td><form action="@Url.Action("Delete", new{ testID = @item.testID})" method="delete"><input type="submit" value="Delete" /></form></td></tr>
}
</table>
</center>
首页控制器.cs
public ActionResult Delete(int id)
{
Table1.Remove(Table1.SingleOrDefault(o => o.testID == id));
return RedirectToAction("uvm");
}
类.cs
public class Table1
{
[Key]
public int testID { get; set; }
public string datetime { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
public class UserViewModel
{
public string errorcode { get; set; }
public List<Table1> thistable { get; set; }
}
您必须调用SaveChanges()
方法来复制您在模型中所做的对数据库所做的更改。您还需要对DbContext
中的实体进行更改。
Entities ent = new Entities(); //This is name of DbConetxt Class
ent.Table1.Remove(ent.Table1.SingleOrDefault(o => o.testID == id));
ent.SaveChanges();