mvc controller 和前一个博客对应

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


namespace MVCBlog.Controllers
{
    //1.控制器类(继承了 Controller)
    public class HomeController : Controller
    {


        #region 0.1 初始化数据集合 +void InitData()
        /// <summary>
        /// 初始化数据集合
        /// </summary>
        public List<Models.Dog> InitData()
        {
            List<Models.Dog> list = new List<Models.Dog>() { 
                new Dog(){ ID=1,Name="小样~~"},
                new Dog(){ ID=2,Name="小样2~~"},
                new Dog(){ ID=3,Name="小样3~~"},
                new Dog(){ ID=4,Name="小样4~~"}
            };
            return list;
        } 
        #endregion


        #region 2.Action方法(可以看成是MVC设计模式的 Model) +ActionResult Index2()
        //2.Action方法(可以看成是MVC设计模式的 Model)
        public ActionResult Index2()
        {
            System.Text.StringBuilder sbHtml = new System.Text.StringBuilder(4000);
            //2.1 处理当前业务(比如读取数据库,判断等)
            //2.1.1创建一个数据集合(伪数据),获取数据
            List<Models.Dog> list = InitData();
            //2.1.2遍历集合,生成html代码,存入 sbHtml
            list.ForEach(d =>
            {
                sbHtml.AppendLine("<div>" + d.ToString() + "</div>");
            });
            //2.2使用ViewBag传输数据给 同名 Index.cshtml 视图
            //ViewBag是一个dynamic类型集合,可以动态添加任意类型的任意名称 的 属性 和 值
            ViewBag.HtmlStr = sbHtml.ToString();
            //2.3加载同名视图index.cshtml
            return View();
        } 
        #endregion


        /// <summary>
        /// 数据上下文对象
        /// </summary>
        OumindBlogEntities db = new OumindBlogEntities();


        #region 0.2 查询 文章 列表 +ActionResult Index()
        /// <summary>
        /// 查询 文章 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //1.查询 数据库里的 文章数据(通过 EF 执行)
            //1.1第一种方式:使用 SQO(标准查询运算符),查询 所有未软删除的文章
            //实际返回的 是一个 IQueryable 对象?此处其实是返回了一个 IQueryable接口的子类对象
            //IQueryable<Models.BlogArticle> query = db.BlogArticles.Where(d => d.AIsDel == false);
            //此时真实 返回的 类型为 DbQuery<T>,支持 延迟加载:只有当使用到数据的时候,才去 查询数据库!
            //DbQuery<Models.BlogArticle> query = (db.BlogArticles.Where(d => d.AIsDel == false)) as DbQuery<Models.BlogArticle>;
            //直接将 返回的 DBQuery转成  List<T>集合,也就是立即查询数据库,并返回查询到的集合
            //List<Models.BlogArticle> list = db.BlogArticles.Where(d => d.AIsDel == false).ToList();


            //1.2第二种方式:使用 Linq 语句,查询 所有为软删除的 文章
            // *Linq 仅仅是 给成员用的 语法糖,.Net编译器会在编译程序集(中间代码)的时候,将Linq语句 转成 SQO(标准查询运算符)
            List<Models.BlogArticle> list = (from d in db.BlogArticles where d.AIsDel == false select d).ToList();


            //2.将集合数据传给视图
            //ViewBag.DataList = list;
            ViewData["DataList"] = list;


            //3.“加载”视图
            return View();
        }
        #endregion


        #region 0.3执行删除操作(根据id) +ActionResult Del(int id)
        /// <summary>
        /// 执行删除操作(根据id)
        /// </summary>
        /// <param name="id">要删除的文章id - /home/del/12 </param>
        /// <returns></returns>
        public ActionResult Del(int id)//此id 会根据 路由的url配置{id}占位符 ,而被 12 替换掉
        {
            try
            {
                //1.创建要删除的对象
                BlogArticle modelDel = new BlogArticle() { AId = id };
                //2.将对象 添加到 EF 管理容器
                db.BlogArticles.Attach(modelDel);
                //3.将对象包装类的 状态 标识为 删除状态
                db.BlogArticles.Remove(modelDel);
                //4.更新到数据库
                db.SaveChanges();
                //5.更新成功,则命令浏览器 重定向 到 /Home/List 方法
                return RedirectToAction("Index","Home");
            }
            catch (Exception ex)
            {
                return Content("删除失败~~~" + ex.Message);
            }
        } 
        #endregion


        #region 0.4 显示要修改的数据 +ActionResult Modify(int id)
        [HttpGet]
        /// <summary>
        /// 0.4 显示要修改的数据
        /// </summary>
        /// <param name="id">要修改的文章的id</param>
        /// <returns></returns>
        public ActionResult Modify(int id)
        {
            //1.根据id 查询数据库,返回的集合中 拿到 第一个 实体对象
            BlogArticle art = (from a in db.BlogArticles where a.AId == id select a).FirstOrDefault();
            //2.生成 文章分类 下拉框 列表集合  <option value="1">文本</option>
            IEnumerable<SelectListItem> listItem = (from c in db.BlogArticleCates
                                          where c.IsDel == false select c).ToList()
                                          .Select(c=> new SelectListItem { Value = c.Id.ToString(), Text = c.Name });
            //将生成的文章分类 下拉框选项集合 设置给 ViewBag
            ViewBag.CateList = listItem;
            
            //List<SelectListItem> list;


            //3.将 art 传递 给 视图显示
            //ViewBag
            //ViewData
            //* “加载”视图,使用View的构造函数,将 数据 传给 视图上的 名为 Model 的 属性
            return View(art);
        } 
        #endregion


        #region 0.5 执行修改 +ActionResult Modify(BlogArticle model)
        [HttpPost]
        /// <summary>

        /// 0.5 执行修改

        ///post请求走给方法

        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Modify(BlogArticle model)
        {
            try
            {
                //1.将实体对象 a.加入 EF 对象容器中,并 b.获取 伪包装类对象
                DbEntityEntry<BlogArticle> entry = db.Entry<BlogArticle>(model);
                //2.将包装类对象的状态设置为 unchanged
                entry.State = System.Data.EntityState.Unchanged;
                //3.设置 被改变的属性
                entry.Property(a => a.ATitle).IsModified = true;
                entry.Property(a => a.AContent).IsModified = true;
                entry.Property(a => a.ACate).IsModified = true;


                //4.提交到数据库 完成修改
                db.SaveChanges();
                //5.更新成功,则命令浏览器 重定向 到 /Home/List 方法
                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                return Content("修改失败~~~" + ex.Message);
            }
        } 
        #endregion
    }
}

猜你喜欢

转载自blog.csdn.net/ma15732625261/article/details/72286735