📅  最后修改于: 2023-12-03 15:36:35.505000             🧑  作者: Mango
在ASP.NET MVC应用程序中,CRUD操作(创建,读取,更新,删除)是常见的任务。这些操作允许应用程序的用户管理其数据。这里将介绍如何使用C#和实体框架来实现基本的CRUD操作。
首先要创建一个ASP.NET MVC应用程序。
在Visual Studio中,打开“解决方案资源管理器”,右键点击解决方案,选择“管理NuGet程序包”选项,搜索并安装以下依赖项:
在web.config
文件中,添加以下连接字符串:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MyDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
修改Data Source
、Initial Catalog
和Integrated Security
选项以连接到您的数据库。
在Models
文件夹中,添加一个名为TodoItem.cs
的新类。
添加以下代码:
using System.ComponentModel.DataAnnotations;
public class TodoItem
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
[Display(Name = "Due Date")]
[DataType(DataType.DateTime)]
public DateTime DueDate { get; set; }
}
此模型表示一个待办事项。
在Controllers
文件夹中,添加一个名为TodoController.cs
的新类。
添加以下代码:
using System;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using MyProject.Models;
namespace MyProject.Controllers
{
public class TodoController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Todo
public ActionResult Index()
{
return View(db.TodoItems.ToList());
}
// GET: Todo/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TodoItem todoItem = db.TodoItems.Find(id);
if (todoItem == null)
{
return HttpNotFound();
}
return View(todoItem);
}
// GET: Todo/Create
public ActionResult Create()
{
return View();
}
// POST: Todo/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Title,Description,DueDate")] TodoItem todoItem)
{
if (ModelState.IsValid)
{
db.TodoItems.Add(todoItem);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(todoItem);
}
// GET: Todo/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TodoItem todoItem = db.TodoItems.Find(id);
if (todoItem == null)
{
return HttpNotFound();
}
return View(todoItem);
}
// POST: Todo/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Description,DueDate")] TodoItem todoItem)
{
if (ModelState.IsValid)
{
db.Entry(todoItem).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(todoItem);
}
// GET: Todo/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TodoItem todoItem = db.TodoItems.Find(id);
if (todoItem == null)
{
return HttpNotFound();
}
return View(todoItem);
}
// POST: Todo/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
TodoItem todoItem = db.TodoItems.Find(id);
db.TodoItems.Remove(todoItem);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
此控制器包含了所有CRUD操作。
在Views
文件夹中,创建一个名为Todo
的文件夹。
在Todo
文件夹中,创建以下视图:
Index.cshtml
Details.cshtml
Create.cshtml
Edit.cshtml
Delete.cshtml
每个视图的代码如下:
Index.cshtml
@model List<MyProject.Models.TodoItem>
<h2>Todo Items</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.DueDate)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.DueDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
Details.cshtml
@model MyProject.Models.TodoItem
<h2>Details</h2>
<table class="table">
<tr>
<th>
#
</th>
<td>
@Html.DisplayFor(model => model.Id)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<td>
@Html.DisplayFor(model => model.Title)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<td>
@Html.DisplayFor(model => model.Description)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.DueDate)
</th>
<td>
@Html.DisplayFor(model => model.DueDate)
</td>
</tr>
</table>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
Create.cshtml
@model MyProject.Models.TodoItem
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TodoItem</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DueDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DueDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DueDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Edit.cshtml
@model MyProject.Models.TodoItem
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TodoItem</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DueDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DueDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DueDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Delete.cshtml
@model MyProject.Models.TodoItem
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>TodoItem</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#
</dt>
<dd>
@Html.DisplayFor(model => model.Id)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Description)
</dt>
<dd>
@Html.DisplayFor(model => model.Description)
</dd>
<dt>
@Html.DisplayNameFor(model => model.DueDate)
</dt>
<dd>
@Html.DisplayFor(model => model.DueDate)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Delete" class="btn btn-danger" />
@Html.ActionLink("Cancel", "Index")
</div>
</div>
}
</div>
在Visual Studio中,按下F5
键运行应用程序。
浏览器将打开应用程序,显示一个包含所有待办事项的列表页面。
在列表页面中,单击“Create New”按钮,创建一个新的待办事项。
通过编辑和删除按钮,对待办事项进行更改和删除。