首页 > 代码库 > Asp.Net MVC EF-DbFirst之增删改查

Asp.Net MVC EF-DbFirst之增删改查

控制器及动作方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc5Test.Models;
using System.Data.Entity.Infrastructure;

namespace Mvc5Test.Controllers
{
    //用户的请求总是先发到控制器的某个Action方法,再由Action方法返回对应的视图
    public class HomeController : Controller
    {
        //数据上下文对象
        BogEntities db = new BogEntities();

        //查询文章
        public ActionResult Index()
        {
            //SQO标准查询运算符
            //DbQuery<ClassType> query = db.ClassTypes.Where(ct => ct.ParentID==0) as DbQuery<ClassType>;
            //List<ClassType> ctList = db.ClassType.Where(ct => ct.ParentID == 0).ToList<ClassType>();

            //Linq
            List<Artical> aList = (from a in db.Artical where a.ClassTypeID != 4 select a).ToList();

            //***使用ViewData传递数据到视图
            ViewData["aList"] = aList;

            return View();
        }

        //删除文章 //此处的默认参数id在App_Start的RouteConfig.cs配置
        public ActionResult Del(int id)
        {
            try
            {
                //1.创建要删除的对象
                Artical a = new Artical { ID = id };
                //2.将对象添加到EF管理容器
                db.Artical.Attach(a);
                //3.将对象包装类的状态标识为删除
                db.Artical.Remove(a);
                //4.更新数据库
                db.SaveChanges();
                //5.更新成功,命令浏览器跳转到列表页
                return RedirectToAction("Index", "Home");
            }
            catch(Exception e)
            {
                return Content("删除失败!!!"+e.Message);
            }
        }

        //修改文章-显示动作
        [HttpGet] //get请求时执行下面这个方法
        public ActionResult Edit(int id)
        {
            //1.根据id查询数据库,返回集合中的第一个对象
            Artical a = (from at in db.Artical where at.ID == id select at).FirstOrDefault();

            //2.生成文章分类数据下拉列表集合
            IEnumerable<SelectListItem> selectList = (from ct in db.ClassType 
                                                      select ct).ToList() //从db.ClassType集合中选取元素形成一个新的集合CT
                                                      .Select(ct => new SelectListItem { Value = http://www.mamicode.com/ct.ID.ToString(), Text = ct.ClassName } //从CT集合中遍历每个元素,并将遍历的每个元素转成SelectListItem对象"Index","Home");
            }
            catch (Exception e)
            {
                return Content("修改失败!!!"+e.Message);
            }
        }

        //新增文章-显示动作
        [HttpGet]
        public ActionResult Add()
        {
            //生成文章分类数据下拉列表集合
            IEnumerable<SelectListItem> selectList = (from ct in db.ClassType
                                                      select ct).ToList() //从db.ClassType集合中选取元素形成一个新的集合CT
                                                      .Select(ct => new SelectListItem { Value = http://www.mamicode.com/ct.ID.ToString(), Text = ct.ClassName } //从CT集合中遍历每个元素,并将遍历的每个元素转成SelectListItem对象"Index", "Home");
            }
            catch (Exception e)
            {
                return Content("新增失败!!!" + e.Message);
            }
        }
    }
}

首页数据列表视图:

@using Mvc5Test.Models;
@{
    Layout = null;
}

<html>
<head>
    <script type="text/javascript">
        function del(id){
            if (confirm("确定要删除吗?")) {
                window.location.href = "http://www.mamicode.com/home/del/" + id;
            }
        }
    </script>
</head>
<body>
    <table>
        <tr>
            <td>id</td>
            <td>title</td>
            <td>class type</td>
            <td>opration</td>
        </tr>
        @foreach (Artical a in ViewData["aList"] as List<Artical>)
        {
            <tr>
                <td>@a.ID</td>
                <td>@a.Title</td>
                <td>@a.ClassType.ClassName</td> <!--a.ClassType是关联自ClassType表ID字段的外键,EF自动进行外键关联查询-->
                <td>
                    <a href="javascript:del(@a.ID)">delete</a>
                    <a href="http://www.mamicode.com/home/edit/@a.ID">edit</a>
                </td>
            </tr>
        }
        <tr>
            <td colspan="4">@Html.ActionLink("新增文章","Add","Home")</td>
        </tr>
    </table>
</body>
</html>

新增视图:

@model Mvc5Test.Models.Artical 
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Add</title>
</head>
<body>
    @using (Html.BeginForm("Add", "Home", FormMethod.Post))
    {
        <table>
            <tr>
                <td colspan="2">新增</td>
            </tr>
            <tr>
                <td>标题:</td>
                <!--使用HtmlHelper的强类型方法直接从Model中根据Title属性生成文本框-->
                <td>@Html.TextBoxFor(a => a.Title)</td>
            </tr>
            <tr>
                <td>分类:</td>
                <!--使用HtmlHelper的强类型方法生成下拉框,并根据Model的ClassTypeID属性设置默认选中项-->
                <td>@Html.DropDownListFor(a => a.ClassTypeID, ViewBag.CtList as IEnumerable<SelectListItem>)</td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="http://www.mamicode.com/确定新增" />
                </td>
                <td>
                    @Html.ActionLink("返回", "Index", "Home")
                </td>
            </tr>
        </table>
    }
</body>
</html>

编辑视图:

@model Mvc5Test.Models.Artical 
<!--以上代码是指定页面Model属性的类型 -->
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    @using (Html.BeginForm("Edit", "Home", FormMethod.Post)) {
        <table>
            <tr>
                <td colspan="2">修改</td>
                @Html.HiddenFor(a => a.ID)
            </tr>
            <tr>
                <td>标题:</td>
                @*<td>@Html.TextBox("Title", (object)Model.Title)</td>*@
                <!--使用HtmlHelper的强类型方法直接从Model中根据Title属性生成文本框-->
                <td>@Html.TextBoxFor(a => a.Title)</td>
            </tr>
            <tr>
                <td>分类:</td>
                <!--使用HtmlHelper的强类型方法生成下拉框,并根据Model的ClassTypeID属性设置默认选中项-->
                <td>@Html.DropDownListFor(a=>a.ClassTypeID,ViewBag.CtList as IEnumerable<SelectListItem>)</td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="http://www.mamicode.com/确定修改" />
                </td>
                <td>
                    @Html.ActionLink("返回","Index","Home")
                </td>
            </tr>
        </table>
    }
</body>
</html>

  

Asp.Net MVC EF-DbFirst之增删改查