MVC Demo 增删查改

本文通过Linq to SQL技术,演示了在MVC框架下如何进行增删查改操作。首先介绍了所需的数据库表Product和Category,然后详细说明了如何创建列表页面,包括在Linq to sql基础上建立TestDB文件与数据库Test的连接,并将数据表导入。接着,逐步讲解了添加页面的代码实现过程。
摘要由CSDN通过智能技术生成

本实例使用Linq to sql.

DB所需要的表:1.Product,2.Category 如下图


1.先创建列表页面


先创建Index 的Control,在Control文件夹下创建ProductControl 文件(在这之前你要使用Linq to sql 创建TestDB文件与DB通信,我这里使用的数据库是Test,并将Product,category 添加到TestDB.dbml文件中)

    public class ProductController : Controller
    {
        //
        // GET: /Product/
        //TESTEntities dbConnect = new TESTEntities();
        TestDBDataContext context = new TestDBDataContext();
        ProductModelView productView = new ProductModelView();

        public ActionResult Index(string searchString)
        {
            var products = from product in context.Products
                           select product;
            if (!string.IsNullOrEmpty(searchString))
            {
                products = products.Where(p => p.ProductName == searchString);
            }
            return View(products.ToList());
        }
    }
在Model 文件夹中创建ProductModelView文件

    public class ProductModelView
    {
        public Product productList { get; set; }
    }
在View文件夹中创建Product文件夹,然后在创建Index.cshtml

@model List<MusicStore.Product>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@Html.ActionLink("New Create", "Create")

@using (Html.BeginForm("Index","Product","Index"))
{
    <p>ProductName:@Html.TextBox("searchString")
    <input type="submit" value ="search" />
    </p>
}

<table>
<tr>
<td>Id</td>
<td>ProductName</td>
<td>CreateTime</td>
<td>Price</td>
<td></td>
</tr>
@foreach (var item in Model)
{
    <tr>
    <td>@item.Id</td>
    <td>@item.ProductName</td>
    <td>@item.CreateTime</td>
    <td>@item.Price</td>
    <td>
    @Html.ActionLink("Edit", "Edit", new { id = item.Id })
    @Html.ActionLink("Delete", "Delete", new { id = item.Id})
    </td>
    </tr>
}
</table>
此时列表页面已经完成

2.创建添加页面


进入ProductControl文件,添加如下代码

        public ActionResult Create()
        {
            ViewBag.categoryList = GetCategoryitems();
            return View();
        }
        [HttpPost]
        public ActionResult AddProduct(Product product)
        {
            context.Products.InsertOnSubmit(product);
            context.SubmitChanges();
            return RedirectToAction("Index");
        }

        public List<SelectListItem> GetCategoryitems()
        {
            var categorys = from category in context.Categories.ToList()
                            select new SelectListItem()
                            {
                                Text = category.CategoryName,
                                Value = category.Id.ToString()
                            };
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem() { Text = "Choose an option" });
            items.AddRange(categorys);
            return items;
        }
然后鼠标放在Create上面创建View

@model MusicStore.Product

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm("AddProduct","Product"))
{
    <fieldset>
    <div>
    @Html.Label("Product")
    </div>
    <div>
    @Html.EditorFor(p =>p.ProductName)
    </div>

    <div>
    @Html.Label("Price")
    </div>
    <div>
    @Html.EditorFor(p =>p.Price)
    </div>

    <div>
    @Html.Label("CreateTime")
    </div>
    <div>
    @Html.EditorFor(p =>p.CreateTime)
    </div>

    <div>
    @Html.Label("ProductCategory")
    </div>
    <div>
    @Html.DropDownListFor(m =>m.ParentId,ViewBag.categoryList as List<SelectListItem>)
    </div>
    <input type="submit" value="Save" />
    </fieldset>
}
3.创建编辑界面

进入ProductControl文件,添加如下代码

        public ActionResult Edit(int Id)
        {
            productView.productList = (from p in context.Products
                                       select p).First(c => c.Id == Id);
            ViewBag.categoryList = GetCategoryitems();
            return View(productView);
        }
        [HttpPost]
        public ActionResult Update(ProductModelView productModel)
        {
            Product product = context.Products.First(p => p.Id == productModel.productList.Id);
            product.ProductName = productModel.productList.ProductName;
            product.Price = productModel.productList.Price;
            product.CreateTime = productModel.productList.CreateTime;
            product.ParentId = productModel.productList.ParentId;
            context.SubmitChanges();

            return RedirectToAction("Index");
        }

然后添加Edit 的View

@model MusicStore.Models.ProductModelView

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Update", "Product"))
{
    <fieldset>
    <legend>Product</legend>
       @Html.HiddenFor(p =>p.productList.Id)
    <p>
        <div>
    @Html.LabelFor(p => p.productList.ProductName)
    </div>
    <div>
    @Html.EditorFor(p => p.productList.ProductName)
    </div>
    </p>

<p>
    <div>
    @Html.LabelFor(p => p.productList.Price)
    </div>
    <div>
    @Html.EditorFor(p => p.productList.Price)
    </div>
</p>

<p>
    <div>
    @Html.LabelFor(p => p.productList.CreateTime)
    </div>
    <div>
    @Html.EditorFor(p => p.productList.CreateTime)
    </div>

    <div>
    @Html.Label("ProductCategory")
    </div>
    <div>
    @Html.DropDownListFor(m => m.productList.ParentId, ViewBag.categoryList as List<SelectListItem>)
    </div>
</p>
    <input type="submit" value="submit" />
    </fieldset>
}
4.添加删除功能

进入ProductControl添加如下代码即可

        public ActionResult Delete(int id)
        {
            Product produt = context.Products.First(p => p.Id == id);
            context.Products.DeleteOnSubmit(produt);
            context.SubmitChanges();
            return RedirectToAction("Index");
        }

此 Demo下载地址请点击 here

好的,我可以为您讲解一下关于MVC架构和EF操作的增删查改MVC是一种软件架构模式,它将应用程序分为三个主要部分:模型(Model)、视图(View)和控制器(Controller)。模型表示应用程序的数据和业务逻辑,视图展示数据给用户,控制器接收用户输入并调用模型和视图进行处理。 EF(Entity Framework)是一个基于.NET Framework的ORM(对象关系映射)框架,它可以使开发人员使用.NET语言编写与数据库交互的代码,而不需要直接与数据库打交道。 下面是关于如何使用MVC架构和EF进行增删查改的示例代码: 1. 增加操作: ```c# [HttpPost] public ActionResult Create(Student student) { using (SchoolContext db = new SchoolContext()) { db.Students.Add(student); db.SaveChanges(); } return RedirectToAction("Index"); } ``` 2. 删除操作: ```c# public ActionResult Delete(int id) { using (SchoolContext db = new SchoolContext()) { Student student = db.Students.Find(id); db.Students.Remove(student); db.SaveChanges(); } return RedirectToAction("Index"); } ``` 3. 修改操作: ```c# [HttpPost] public ActionResult Edit(Student student) { using (SchoolContext db = new SchoolContext()) { db.Entry(student).State = EntityState.Modified; db.SaveChanges(); } return RedirectToAction("Index"); } ``` 4. 查询操作: ```c# public ActionResult Details(int id) { using (SchoolContext db = new SchoolContext()) { Student student = db.Students.Find(id); return View(student); } } ``` 以上是关于MVC架构和EF操作的增删查改的示例代码,希望能对您有所帮助。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值