八、Asp.Net MVC4.0 CMSシステムケースを開発するコラム内容モデル管理


サイトのバックグラウンドにはコラム管理機能があり、コラム管理にはコラム内容モジュール項目があります.例えば、サイトの各コラムをニュースモジュール、画像モジュール、文章モジュール、製品モジュールなどに分けます.
カラムのモデルカテゴリ管理には、モジュール名、モジュールタイプ、有効化の有無、説明などが含まれます.
一、Models属性:
using System.Linq;
using System.Web;

namespace Hillstone.Models
{
    public class SysCategoryModel
    {
        [Key]
        public int ModelID { get; set; }

        [Display(Name="    ")]
        [Required(ErrorMessage="×")]
        [StringLength(50,ErrorMessage="×")]
        public string ModelName { get; set; }

        [Display(Name = "    ")]
        [Required(ErrorMessage = "×")]
        [StringLength(50, ErrorMessage = "×")]
        public string ModelType { get; set; }

        [Display(Name="    ")]
        [Required(ErrorMessage = "×")]
        public bool Enable{ get; set; }

        [Display(Name="    ")]
        [StringLength(100,ErrorMessage="×")]
        public string Description{ get; set; }
        
    }
}

≪有効化|Enable|ldap≫:有効化されていない場合、このタイプの欄は使用できません.
二、DALデータ層:エンティティデータセットへのアクセスまたは設定
public DbSet<SysCategoryModel> categoryModel { get; set; }

三、BLL業務ロジック層:読取、新規、編集、削除、表示機能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Hillstone.Models;
using System.Data.Entity;
using Hillstone.DAL;

namespace Hillstone.BLL
{
    public class SysCategoryModelReponsitory : IRepositoryBase<SysCategoryModel>
    {
        private HillstoneContext db = new HillstoneContext();

        /// <summary>
        ///       
        /// </summary>
        /// <returns></returns>
        public IQueryable<SysCategoryModel> List()
        {
            var _categoryModel = db.categoryModel;
            return _categoryModel;
        }

        /// <summary>
        ///         
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public override SysCategoryModel Find(int Id)
        {
            var _categoryModel = db.categoryModel.SingleOrDefault(c => c.ModelID == Id);
            return _categoryModel;
        }

        /// <summary>
        ///         
        /// </summary>
        /// <param name="Tmodel"></param>
        /// <returns></returns>
        public override bool Add(SysCategoryModel Tmodel)
        {
            db.categoryModel.Add(Tmodel);
            if (db.SaveChanges() > 0)
            {
                return true;
            }
            else {
                return false;
            }
        }

        /// <summary>
        ///         
        /// </summary>
        /// <param name="Id">ID</param>
        /// <returns></returns>
        public override bool Delete(int Id)
        {
            var _categoryModel = db.categoryModel.FirstOrDefault(c => c.ModelID == Id);
            if (_categoryModel != null)
            {
                return Delete(_categoryModel);
            }
            else {
                return false;
            }
            
        }

        /// <summary>
        ///         
        /// </summary>
        /// <param name="sysCategoryModel">    </param>
        /// <returns></returns>
        public bool Delete( SysCategoryModel sysCategoryModel)
        {
            db.categoryModel.Remove(sysCategoryModel);
            if (db.SaveChanges() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        ///       
        /// </summary>
        /// <param name="Tmodel">      </param>
        /// <returns></returns>
        public override bool Update(SysCategoryModel Tmodel)
        {
            db.categoryModel.Attach(Tmodel);
            db.Entry<SysCategoryModel>(Tmodel).State = System.Data.Entity.EntityState.Modified;
            if(db.SaveChanges()>0){
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}

注:編集時に参照する
using System.Data.Entity;

使用可能
            db.Entry<SysCategoryModel>(Tmodel).State = System.Data.Entity.EntityState.Modified;

四、コントローラ:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Hillstone.BLL;
using Hillstone.Models;

namespace Hillstone.Controllers.Sys.Cotegory
{
    public class CategoryModelController : Controller
    {
        private SysCategoryModelReponsitory categoryModelRsy = new SysCategoryModelReponsitory();

        /// <summary>
        ///     
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
           var _categoryModel = categoryModelRsy.List();
           return View(_categoryModel);
        }

        /// <summary>
        ///     
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            return View();
        }

        /// <summary>
        ///       
        /// </summary>
        /// <param name="sysCategoryModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SysCategoryModel sysCategoryModel)
        {
            if (ModelState.IsValid)
            {
                if (categoryModelRsy.Add(sysCategoryModel))
                {
                    ModelState.AddModelError("Message", "  !");
                }
                else
                {
                    ModelState.AddModelError("Message", "  !");
                }
            }
            return View();
        }

        /// <summary>
        ///     
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var categoryModel = categoryModelRsy.Find(id);
            return View(categoryModel);
        }

        /// <summary>
        ///       
        /// </summary>
        /// <param name="sysCategoryModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(SysCategoryModel sysCategoryModel)
        {
            if (ModelState.IsValid) {
                if (categoryModelRsy.Update(sysCategoryModel))
                {
                    ModelState.AddModelError("Message", "  !");
                }
                else {
                    ModelState.AddModelError("Message","  !");
                }
            }
            return View();
        }

        /// <summary>
        ///     
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(int id)
        {
            var _sysCategoryModel = categoryModelRsy.Find(id);
            return View(_sysCategoryModel);
        }

        /// <summary>
        ///       
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (categoryModelRsy.Delete(id))
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
            }
            else
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.NotFound);
            }
        }
        //AJAX    
        [HttpPost]
        public JsonResult DeleteAsJson(int id)
        {
            var _categoryModel = categoryModelRsy.Find(id);
            if (categoryModelRsy != null)
            {
                return Json(categoryModelRsy.Delete(id);
            }
            else
            {
                return Json(false);
            }
        }
    }
}

五、ビューページ
1、表示リスト:主にJson削除機能の実現
@model IEnumerable<Hillstone.Models.SysCategoryModel>

@{
    ViewBag.Title = "List";
    Layout = "~/Views/Shared/_Layout.cshtml";    
}

@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">

        function DeleteAsJson(id,name)
        {
            if (confirm("      " + name + "?")) {
                $.post("@Url.Action("DeleteAsJson","CategoryModel")", { Id: id }, function (data) {
                            if (data) {
                                alert("    !");
                                location.reload();
                            }
                        })
            }
        }

@*        $("#btn_del").click(function () {
            if (confirm("          ?
!")) {                 $.post("@Url.Action("ManageDeleteJson","Category")", { id: $("#CategoryId").val() }, function (data) {                 if (data) {                     alert(" !");                     top.location = "@Url.Action("Manage", "Category")";                 }                 else {                     alert(" ! 。");                 }             });         }         });*@     </script>     } <h2>List</h2> <p>     @Html.ActionLink("Create New", "Create") </p> <table>     <tr>         <th>             @Html.DisplayNameFor(model => model.ModelName)         </th>         <th>             @Html.DisplayNameFor(model => model.ModelType)         </th>         <th>             @Html.DisplayNameFor(model => model.Enable)         </th>         <th>             @Html.DisplayNameFor(model => model.Description)         </th>         <th></th>     </tr> @foreach (var item in Model) {     <tr>         <td>             @Html.DisplayFor(modelItem => item.ModelName)         </td>         <td>             @Html.DisplayFor(modelItem => item.ModelType)         </td>         <td>             @Html.DisplayFor(modelItem => item.Enable)         </td>         <td>             @Html.DisplayFor(modelItem => item.Description)         </td>         <td>             @Html.ActionLink(" ", "Edit", new { id=item.ModelID })              @Html.ActionLink(" ", "Details", new { id=item.ModelID }) |             <a id="btn_del" href="javascript:void(0)" onclick="DeleteAsJson(@item.ModelID,'@item.ModelName')"> </a>         </td>     </tr> } </table>

他のページは基本的に変わらない.