ASP.NET MVC 实现增删改查(CRUD)操作的完整示例

提供一个完整的 ASP.NET MVC 实现增删改查(CRUD)操作的示例。该示例使用 SQL Server 数据库,以一个简单的 Product 实体为例。

步骤 1:创建 ASP.NET MVC 项目

首先,在 Visual Studio 中创建一个新的 ASP.NET MVC 项目。

步骤 2:定义数据模型

Models 文件夹下创建 Product.cs 文件:

csharp

复制代码
using System.ComponentModel.DataAnnotations;

namespace YourNamespace.Models
{
    public class Product
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public decimal Price { get; set; }
    }
}

步骤 3:创建数据库上下文

Models 文件夹下创建 ProductContext.cs 文件:

csharp

复制代码
using Microsoft.EntityFrameworkCore;

namespace YourNamespace.Models
{
    public class ProductContext : DbContext
    {
        public ProductContext(DbContextOptions<ProductContext> options) : base(options)
        {
        }

        public DbSet<Product> Products { get; set; }
    }
}

步骤 4:配置数据库连接

appsettings.json 文件中添加数据库连接字符串:

json

复制代码
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

步骤 5:在 Startup.cs 中配置数据库上下文

csharp

复制代码
using Microsoft.EntityFrameworkCore;
using YourNamespace.Models;

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ProductContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddControllersWithViews();
}

步骤 6:创建控制器

Controllers 文件夹下创建 ProductController.cs 文件:

csharp

复制代码
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
using System.Linq;

namespace YourNamespace.Controllers
{
    public class ProductController : Controller
    {
        private readonly ProductContext _context;

        public ProductController(ProductContext context)
        {
            _context = context;
        }

        // 显示所有产品
        public IActionResult Index()
        {
            var products = _context.Products.ToList();
            return View(products);
        }

        // 创建产品视图
        public IActionResult Create()
        {
            return View();
        }

        // 处理创建产品的 POST 请求
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                _context.Products.Add(product);
                _context.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }

        // 编辑产品视图
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var product = _context.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            return View(product);
        }

        // 处理编辑产品的 POST 请求
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, Product product)
        {
            if (id != product.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(product);
                    _context.SaveChanges();
                }
                catch
                {
                    if (!ProductExists(product.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }

        // 删除产品确认视图
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var product = _context.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            return View(product);
        }

        // 处理删除产品的 POST 请求
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            var product = _context.Products.Find(id);
            _context.Products.Remove(product);
            _context.SaveChanges();
            return RedirectToAction(nameof(Index));
        }

        private bool ProductExists(int id)
        {
            return _context.Products.Any(e => e.Id == id);
        }
    }
}

步骤 7:创建视图

Views 文件夹下创建 Product 文件夹,并在其中创建以下视图文件:

Index.cshtml

html

复制代码
@model IEnumerable<YourNamespace.Models.Product>

@{
    ViewData["Title"] = "Product List";
}

<h1>Product List</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Price)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
            </tr>
        }
    </tbody>
</table>
Create.cshtml

html

复制代码
@model YourNamespace.Models.Product

@{
    ViewData["Title"] = "Create Product";
}

<h1>Create Product</h1>

<form asp-action="Create">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Name">Name</label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Price">Price</label>
        <input asp-for="Price" class="form-control" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Create</button>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>
Edit.cshtml

html

复制代码
@model YourNamespace.Models.Product

@{
    ViewData["Title"] = "Edit Product";
}

<h1>Edit Product</h1>

<form asp-action="Edit">
    <input type="hidden" asp-for="Id" />
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Name">Name</label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Price">Price</label>
        <input asp-for="Price" class="form-control" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>
Delete.cshtml

html

复制代码
@model YourNamespace.Models.Product

@{
    ViewData["Title"] = "Delete Product";
}

<h1>Delete Product</h1>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Product</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Price)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Price)
        </dd>
    </dl>

    <form asp-action="DeleteConfirmed">
        <input type="hidden" asp-for="Id" />
        <button type="submit" class="btn btn-danger">Delete</button> |
        <a asp-action="Index">Back to List</a>
    </form>
</div>

步骤 8:运行项目

运行项目,访问 Product 控制器的 Index 动作,你将看到产品列表页面,并可以进行增删改查操作。

相关推荐
盖世英雄酱581364 分钟前
同事说缓存都用redis啊,数据不会丢失!真的吗?
redis·后端·面试
L2ncE1 小时前
双非计算机自救指南(找工作版)
后端·面试·程序员
cdg==吃蛋糕1 小时前
solr自动建议接口简单使用
后端·python·flask
Joseit2 小时前
基于 Spring Boot实现的图书管理系统
java·spring boot·后端
{⌐■_■}2 小时前
【go】什么是Go语言的GPM模型?工作流程?为什么Go语言中的GMP模型需要有P?
java·开发语言·后端·golang
IT杨秀才2 小时前
LangChain框架入门系列(5):Memory
人工智能·后端·langchain
程序猿chen3 小时前
JVM考古现场(二十四):逆熵者·时间晶体的永恒之战
java·jvm·git·后端·程序人生·java-ee·改行学it
AronTing3 小时前
单例模式:确保唯一实例的设计模式
java·javascript·后端
AronTing3 小时前
模板方法模式:定义算法骨架的设计模式
java·后端·面试
AronTing3 小时前
迭代器模式:统一数据遍历方式的设计模式
java·后端·面试