📜  使用C#和实体框架的ASP.NET MVC中的基本CRUD(创建,读取,更新,删除)(1)

📅  最后修改于: 2023-12-03 15:36:35.505000             🧑  作者: Mango

使用C#和实体框架的ASP.NET MVC中的基本CRUD

在ASP.NET MVC应用程序中,CRUD操作(创建,读取,更新,删除)是常见的任务。这些操作允许应用程序的用户管理其数据。这里将介绍如何使用C#和实体框架来实现基本的CRUD操作。

准备工作
  1. 首先要创建一个ASP.NET MVC应用程序。

  2. 在Visual Studio中,打开“解决方案资源管理器”,右键点击解决方案,选择“管理NuGet程序包”选项,搜索并安装以下依赖项:

    • EntityFramework
    • Microsoft.AspNet.Mvc
    • Microsoft.AspNet.WebApi.Core
  3. web.config文件中,添加以下连接字符串:

    <connectionStrings>
      <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MyDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    修改Data SourceInitial CatalogIntegrated Security选项以连接到您的数据库。

创建模型
  1. Models文件夹中,添加一个名为TodoItem.cs的新类。

  2. 添加以下代码:

    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; }
    }
    

    此模型表示一个待办事项。

创建控制器
  1. Controllers文件夹中,添加一个名为TodoController.cs的新类。

  2. 添加以下代码:

    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操作。

创建视图
  1. Views文件夹中,创建一个名为Todo的文件夹。

  2. 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>
      
运行应用程序
  1. 在Visual Studio中,按下F5键运行应用程序。

  2. 浏览器将打开应用程序,显示一个包含所有待办事项的列表页面。

  3. 在列表页面中,单击“Create New”按钮,创建一个新的待办事项。

  4. 通过编辑和删除按钮,对待办事项进行更改和删除。