GridView 组件不适用于 ASP.NET MVC 应用程序。该组件严重依赖 ViewState 和 PostBack,它们是 ASP.NET MVC 中不再存在的概念。
您可以使用WebGrid helper
来在视图中显示记录并提供删除功能。
因此,第一步是设计一个模型,该模型将代表您希望在视图中显示的记录:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SocialSecurity { get; set; }
}
然后下一步是有一个数据层,它将查询您的关系数据库并提取模型。您可以使用诸如实体框架之类的 ORM 来简化此任务,或者直接使用普通的 ADO.NET,这就是我将在此处说明的内容:
public class PeopleRepository
{
public IList<Person> Get()
{
var connectionString = ConfigurationManager
.ConnectionString["SomeConnectionStringKey"]
.ConnectionString;
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id, fname, lname, ssn FROM people";
using (var reader = cmd.ExecuteReader())
{
var result = new List<Person>();
while (reader.Read())
{
result.Add(new Person
{
Id = reader.GetInt32(reader.GetOrindal("id")),
FirstName = reader.GetString(reader.GetOrindal("fname")),
LastName = reader.GetString(reader.GetOrindal("lname")),
SocialSecurity = reader.GetString(reader.GetOrindal("ssn"))
});
}
return result;
}
}
}
public void Delete(int id)
{
var connectionString = ConfigurationManager
.ConnectionString["SomeConnectionStringKey"]
.ConnectionString;
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "DELETE FROM people WHERE id = @id";
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
}
}
}
下一步是有一个控制器来连接你的模型和视图:
public class PeopleController: Controller
{
private readonly PeopleRepository repo = new PeopleRepository();
public ActionResult Index()
{
IList<Person> model = repo.Get();
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
repo.Delete(id);
IList<Person> model = repo.Get();
return View("Index", model);
}
}
最后一步当然是视图:
@model IList<Person>
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml(
columns: grid.Columns(
grid.Column(columnName: "Id"),
grid.Column(columnName: "FirstName", header: "First name"),
grid.Column(columnName: "LastName", header: "Last name"),
grid.Column(columnName: "SocialSecurity", header: "Social Security Number"),
grid.Column(
header: "",
format:
@<text>
<form action="@Url.Action("Delete", "People", new { id = item.Id })" method="post" onsubmit="return confirm('Are you sure you want to delete this person?');">
<button type="submit">Delete</button>
</form>
</text>
)
)
)