MVC实现增删查改

本文详细介绍如何在ASP.NET MVC项目中使用Northwind.edmx数据模型进行增删查改操作,包括控制器代码实现及视图创建步骤。

1.添加Northwind.edmx(ADO.NET Entity Data Model).

2. 在HomeController中添加如下代码:

    [HandleError]
    public class HomeController : Controller
    {
        NorthwindEntities NorthWind = new NorthwindEntities();
        public ActionResult Index()
        {
            var model = NorthWind.Categories.ToList();
            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            // 返回集合中的第一个元素,其实质就是在SQL语句中加TOP (1)。
            var model = NorthWind.Categories.First(c => c.CategoryID == id);
            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id,FormCollection form)
        {
            var model = NorthWind.Categories.First(c => c.CategoryID == id);
            UpdateModel(model,new []{"CategoryName","Description"});
            NorthWind.SaveChanges();
            return RedirectToAction("Index");
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Details(int id)
        {
            var model = NorthWind.Categories.First(c => c.CategoryID == id);
            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create()
        {
            Categories categories=new Categories();
            return View(categories);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(int CategoryID,FormCollection form)
        {
            //当序列中可能找不到满足条件的元素时,使用FirstOrDefault方法,然后,一定要对返回值是否为null,进行不同的处理
            var model = NorthWind.Categories.FirstOrDefault(c => c.CategoryID == CategoryID);
            if (model==null)
            {
                Categories categories=new Categories();
                UpdateModel(categories,new[]{"CategoryName","Description"});
                NorthWind.AddToCategories(categories);
                NorthWind.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Create");
            }
        }
        public ActionResult About()
        {
            return View();
        }
    }


3.在Index处右键,然后Add View,如下图:

MVC

 

4. 用以上方法依次添加增删查改

 

MVC模式的实现对数据库的增删改查 部分代码: package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import common.DBConnection; import bean.Contact; public class ContactDAO { public List getAllContact() throws Exception{ Connection conn=DBConnection.getConntion(); PreparedStatement ps=conn.prepareStatement("select * from Contact"); ResultSet rs=ps.executeQuery(); List list = new ArrayList(); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String phone = rs.getString("phone"); String address = rs.getString("address"); Contact c = new Contact(); c.setId(id); c.setName(name); c.setPhone(phone); c.setAddress(address); list.add(c); } rs.close(); ps.close(); conn.close(); return list; } public void addContact(String name,String phone,String address) throws Exception{ String sql = "insert into contact(id,name,phone,address) values(seq_contact.nextval,?,?,?)"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, phone); pstmt.setString(3, address); pstmt.executeUpdate(); } public void delContact(int id) throws Exception{ String sql = "delete from contact where id=?"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); pstmt.executeUpdate(); } public Contact getContactById(int id) throws Exception{ String sql = "select * from Contact where id=?"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); Contact c = null; while(rs.next()){ // int id = rs.getInt("id"); String name=rs.getString("name"); String p
### ASP.NET MVC 实现 CRUD 操作的源码示例 #### 创建模型类 首先,在`Models`文件夹下创建一个名为`Product.cs`的实体类。 ```csharp using System; namespace MvcShell.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public DateTime CreatedDate { get; set; } = DateTime.Now; } } ``` #### 配置数据库上下文 接着配置Entity Framework用于连接并操作MySQL数据库。在项目中添加一个新的类`ApplicationContext.cs`来表示数据库上下文[^4]。 ```csharp using Microsoft.EntityFrameworkCore; public class ApplicationContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionString = "server=localhost;database=aspnetmvc_crud;uid=root;pwd=password;"; optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); } } ``` #### 控制器逻辑编写 控制器负责处理HTTP请求并将业务逻辑传递给视图层显示。这里展示的是`ProductsController.cs`的部分方法实现,包括新增、编辑、删除以及查询产品列表的功能[^2]。 ```csharp using System.Linq; using Microsoft.AspNetCore.Mvc; using MvcShell.Models; public class ProductsController : Controller { private readonly ApplicationContext _context; public ProductsController(ApplicationContext context) { _context = context; } // GET: /products/ public IActionResult Index() { return View(_context.Products.ToList()); } // POST: /products/create [HttpPost] public IActionResult Create(Product product) { if (ModelState.IsValid) { _context.Add(product); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } return View(product); } // GET: /products/edit/5 public IActionResult Edit(int? id) { if (id == null || !_context.Products.Any(e => e.Id == id)) { return NotFound(); } var product = _context.Products.Find(id); return View(product); } // POST: /products/delete/5 [HttpPost, ActionName("Delete")] public IActionResult DeleteConfirmed(int id) { var product = _context.Products.Find(id); if (product != null) { _context.Products.Remove(product); _context.SaveChanges(); } return RedirectToAction(nameof(Index)); } } ``` #### 视图页面构建 对于每一个动作(Action),都需要相应的Razor视图文件来进行UI渲染。以下是部分简化版的HTML+Razor语法混合使用的例子: - `Index.cshtml`: 列表页 - `Create.cshtml`: 新建记录页 - `Edit.cshtml`: 修改现有条目页 这些视图通常位于Views目录下的相应子文件夹内,比如这里的视图应该放在`Views/Products/Index.cshtml`等位置[^1]。 ```razor <!-- Views/Products/Create.cshtml --> @model MvcShell.Models.Product <form asp-action="Create"> <!-- 输入框和其他控件省略... --> </form> ``` 通过上述代码片段可以看出,整个过程涉及到了从数据访问到表现层的设计模式应用,同时也体现了ASP.NET MVC架构的优势所在——清晰的角色分离与良好的可维护性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值