MVC4做网站后台:栏目管理1、添加栏目-续

栏目类型跟原来一样分为常规栏目、单页栏目和外部链接。根据栏目类型的不同要隐藏相应的表单和验证(服务器端验证)。另外一个是父栏目必须是常规栏目才行,easyui-combotree要用到树形json数据,考虑不用递归函数而是用ParentPath字段排序的方式实现。

 

首先在在【CategoryController】中添加这个action,代码

/// <summary>
        /// 栏目树
        /// </summary>
        /// <param name="categoryId">栏目Id,调用所有栏目为0</param>
        /// <param name="categoryType">栏目类型-1所有栏目,0常规栏目</param>
        /// <param name="jsonType">返回的数据类型【默认(0)-EasyuiTree类型】</param>
        /// <returns>Json类型数据</returns>
        public JsonResult Tree(int categoryId = 0, int categoryType = 0, int jsonType = 0)
        {
            IQueryable<Category> _categorys;
            if (categoryType == -1) _categorys = categoryRepository.Progeny(categoryId).OrderByDescending(c => c.ParentPath).ThenBy(c => c.Order);
            else _categorys = categoryRepository.Progeny(categoryId, categoryType).OrderByDescending(c => c.ParentPath).ThenBy(c => c.Order);
            switch (jsonType)
            {
                default:
                    List<EasyuiTreeNodeViewModel> _trees = new List<EasyuiTreeNodeViewModel>();
                    Dictionary<int, EasyuiTreeNodeViewModel> _nodes = new Dictionary<int, EasyuiTreeNodeViewModel>();
                    foreach (var _category in _categorys)
                    {
                        if (_trees.Exists(n => n.parentid == _category.CategoryId))//存在子节点
                        {
                            var _childern = _trees.Where(n => n.parentid == _category.CategoryId).ToList();
                            _trees.RemoveAll(n => n.parentid == _category.CategoryId);
                            _trees.Add(new EasyuiTreeNodeViewModel { parentid = _category.ParentId, id = _category.CategoryId, text = _category.Name, state = "open", children = _childern });
                        }
                        else _trees.Add(new EasyuiTreeNodeViewModel { parentid = _category.ParentId, id = _category.CategoryId, text = _category.Name, state = "close"});
                    }
                    return Json(_trees);
            }
        }

 

再在控制器中添加Add的局部视图方法

/// <summary>
        /// 添加栏目
        /// </summary>
        /// <returns>局部视图</returns>
        public PartialViewResult Add()
        {
            return PartialView(new Category { CategoryView = "Index", ContentOrder = 0, ContentView = "Detail", Model = "", Order = 0, PageSize = 20, ParentId = 0, RecordName = "文章", RecordUnit = "", Type = 0 });
        }
右键添加强类型局部视图

@model Ninesky.Models.Category
<div class="c_navbar">栏目管理 >> 添加栏目</div>
@using (Html.BeginForm("Add", "Category", FormMethod.Post, new { id = "categoryadd_form" }))
{
    @Html.AntiForgeryToken()
    <div class="fs_wapper">
        <div class="header">添加栏目</div>
        @Html.ValidationSummary()
        <table class="fieldset">
            <tr>
                <th>@Html.LabelFor(model => model.Name)<span>*</span></th>
                <td>@Html.EditorFor(model => model.Name)
                    @Html.ValidationMessageFor(model => model.Name)
                    @Html.DisplayDescriptionFor(model => model.Name)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.ParentId)<span>*</span></th>
                <td>
                    <input id="ParentId" name="ParentId" style="width: 200px;" data-url="@Url.Action("Tree", "Category")" value="@Model.ParentId" />
                    @Html.ValidationMessageFor(model => model.ParentId)
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.Type)<span>*</span></th>
                <td>
                    <input id="Type" name="Type" value="@Model.Type" />
                    @Html.ValidationMessageFor(model => model.Type)
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.Model)<span>*</span></th>
                <td>
                    <input id="Model" name="Model" value="@Model.Model" data-url="@Url.Action("Items", "Module", new { id = 1 })" />
                    @Html.ValidationMessageFor(model => model.Model)
                    @Html.DisplayDescriptionFor(model => model.Model)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.CategoryView)<span>*</span></th>
                <td>
                    <input id="CategoryView" class="easyui-combobox" name="CategoryView" data-options="valueField:'Name',textField:'Name',url:'@Url.Action("Views", "View", new { controllerName="Category" })'" value="@Model.CategoryView">
                    @Html.ValidationMessageFor(model => model.CategoryView)
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.ContentView)<span>*</span></th>
                <td>
                    <input id="ContentView" class="easyui-combobox" name="ContentView" data-url="@Url.Action("Views", "View")" data-options="valueField:'Name',textField:'Name',url:'@Url.Action("Views", "Category", new { controllerName="Article" })'" value="@Model.ContentView">
                    @Html.ValidationMessageFor(model => model.CategoryView)
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.LinkUrl)<span>*</span></th>
                <td>
                    @Html.EditorFor(model => model.LinkUrl)
                    @Html.ValidationMessageFor(model => model.LinkUrl)
                    @Html.DisplayDescriptionFor(model => model.LinkUrl)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.Order)<span>*</span></th>
                <td>
                    @Html.EditorFor(model => model.Order)
                    @Html.ValidationMessageFor(model => model.Order)
                    @Html.DisplayDescriptionFor(model => model.Order)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.ContentOrder)<span>*</span></th>
                <td>
                    <select id="ContentOrder" name="ContentOrder" class="easyui-combobox" style="width: 200px;"
                        data-options="url:'@Url.Action("OrderList", "Item", new {area="" })',valueField:'Value',textField:'Name'">
                    </select>
                    @Html.ValidationMessageFor(model => model.ContentOrder)
                    @Html.DisplayDescriptionFor(model => model.ContentOrder)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.PageSize)<span>*</span></th>
                <td>
                    @Html.EditorFor(model => model.PageSize)
                    @Html.ValidationMessageFor(model => model.PageSize)
                    @Html.DisplayDescriptionFor(model => model.PageSize)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.RecordUnit)<span>*</span></th>
                <td>
                    @Html.EditorFor(model => model.RecordUnit)
                    @Html.ValidationMessageFor(model => model.RecordUnit)
                    @Html.DisplayDescriptionFor(model => model.RecordUnit)
                    
                </td>
            </tr>
            <tr>
                <th>@Html.LabelFor(model => model.RecordName)<span>*</span></th>
                <td>
                    @Html.EditorFor(model => model.RecordName)
                    @Html.ValidationMessageFor(model => model.Name)
                    @Html.DisplayDescriptionFor(model => model.RecordName)
                    
                </td>
            </tr>
            <tr>
                <th></th>
                <td>
                    <a id="CategoryAdd_Save" href="javascript:void()" class="easyui-linkbutton">保存</a>
                </td>
            </tr>
        </table>
    </div>
    @Scripts.Render("~/Areas/Admin/Scripts/Category.js");
    <script type="text/javascript">
        CategoryAddReady();
    </script>
}
@Scripts.Render("~/bundles/jqueryval")

在category.js中添加相应的js函数

//Add视图添加载完成函数
function CategoryAddReady() {
    $.post($('#ParentId').attr('data-url'), null, function (data) {
        if (data == "") data = [{ id: 0, text: "无" }];
        else {
            data.unshift({ id: 0, text: "无" });
        }
        $('#ParentId').combotree({ required: true, data: data });

    });
    $('#Type').combobox({
        valueField: 'id',
        textField: 'text',
        data: [{ 'id': 0, 'text': '常规栏目' }, { 'id': 1, 'text': '单页栏目' }, { 'id': 2, 'text': '外部链接' }],
        required: true,
        onSelect: function (rec) {
            CategoryAdd_TypeChange(rec.id);
        }
    });
    $.post($('#Model').attr("data-url"), null, function (data) {
        if (data == "") data = [{ Model: "", Name: "无" }];
        else {
            data.unshift({ Model: "", Name: "无" });
        }
        $('#Model').combobox({
            valueField: 'Model',
            textField: 'Name',
            data: data,
            required: true,
            onSelect: function (rec) {
                CategoryAdd_ModelChange(rec.Model);
            }
        });
    });

    $('#ContentView').parent().parent().hide();
    $('#LinkUrl').parent().parent().hide();
    $('#ContentOrder').parent().parent().hide();
    $('#RecordUnit').parent().parent().hide();
    $('#PageSize').parent().parent().hide();
    $('#RecordName').parent().parent().hide();
    //保存事件
    $('#CategoryAdd_Save').click(function () {
        CategoryAdd_Save();
    });
    //CategoryAdd_TypeChange(0);
}
//Add视图类型切换事件
function CategoryAdd_TypeChange(typeId) {
    //常规栏目
    if (typeId == 0) {
        //模型
        $('#Model').parent().parent().show();
        var _modelValue = $('#Model').combobox('getValue');
        CategoryAdd_ModelChange(_modelValue);

    }//单页栏目
    else if (typeId == 1) {
        //模型
        $('#Model').parent().parent().hide();
        //栏目视图
        $('#CategoryView').parent().parent().show();
        //内容视图
        $('#ContentView').parent().parent().hide();
        //链接地址
        $('#LinkUrl').parent().parent().hide();
        //内容排序
        $('#ContentOrder').parent().parent().hide();
        //每页记录数
        $('#PageSize').parent().parent().hide();
        //记录单位
        $('#RecordUnit').parent().parent().hide();
        //记录名称
        $('#RecordName').parent().parent().hide();
    }//外部链接
    else if (typeId == 2) {
        //模型
        $('#Model').parent().parent().hide();
        //栏目视图
        $('#CategoryView').parent().parent().hide();
        //内容视图
        $('#ContentView').parent().parent().hide();
        //链接地址
        $('#LinkUrl').parent().parent().show();
        //内容排序
        $('#ContentOrder').parent().parent().hide();
        //每页记录数
        $('#PageSize').parent().parent().hide();
        //记录单位
        $('#RecordUnit').parent().parent().hide();
        //记录名称
        $('#RecordName').parent().parent().hide();
    }
}

//Add视图模型切换事件
function CategoryAdd_ModelChange(value) {
    if (value == "")//模型为无
    {
        //栏目视图

        $('#CategoryView').parent().parent().show();
        //内容视图
        $('#ContentView').parent().parent().hide();
        //链接地址
        $('#LinkUrl').parent().parent().hide();
        //内容排序
        $('#ContentOrder').parent().parent().hide();
        //每页记录数
        $('#PageSize').parent().parent().hide();
        //记录单位
        $('#RecordUnit').parent().parent().hide();
        //记录名称
        $('#RecordName').parent().parent().hide();
    }
    else {
        $('#CategoryView').parent().parent().show();
        //内容视图
        $('#ContentView').parent().parent().show();
        //链接地址
        $('#LinkUrl').parent().parent().hide();
        //内容排序
        $('#ContentOrder').parent().parent().show();
        //每页记录数
        $('#PageSize').parent().parent().show();
        //记录单位
        $('#RecordUnit').parent().parent().show();
        //记录名称
        $('#RecordName').parent().parent().show();
        var _modelValue = $('#Model').combobox('getValue');
        $('#ContentView').combobox('reload', $('#ContentView').attr('data-url') + '?controllerName=' + _modelValue);
    }
}
//添加保存
function CategoryAdd_Save() {
    $('#categoryadd_form').form('submit', {
        success: function (data) {
            var rt = jQuery.parseJSON(data);
            //验证
            Authentication(data.Authentication);
            //操作成功
            if (rt.Success) {
                $(document.body).append("<div id='CategoryAdd_SuccessDialog'></div>");
                $('#CategoryAdd_SuccessDialog').dialog({
                    title: '操作成功',
                    width: 280,
                    height: 138,
                    closed: false,
                    cache: false,
                    content: '<br />添加栏目成功',
                    modal: true,
                    buttons:[{
                        text:'继续添加栏目',
                        handler: function () {
                            var _layout = $('#layout');
                            var _center = _layout.layout('panel', 'center');
                            _center.panel('refresh');
                            var _west = _layout.layout('panel', 'west');
                            _west.panel('refresh');
                            $('#CategoryAdd_SuccessDialog').dialog('destroy');
                        }
                    },{
                        text:'关闭',
                        handler: function () {
                            var _layout = $('#layout');
                            var _west = _layout.layout('panel', 'west');
                            _west.panel('refresh');
                            $('#CategoryAdd_SuccessDialog').dialog('destroy');
                        }
                    }]
                });
            }
            else {
                var msg = "";
                if (rt.ValidationList != undefined) ShowValidationMessage(rt.ValidationList);
                if (msg != "") msg = rt.Message + "<br /> <p> 原因如下:" + "<ul>" + msg + "</ul></p>";
                else msg = rt.Message;
                $.messager.alert("添加栏目失败", msg, "error");
            }
        }
    });
}

再次在控制器中添加处理action

[HttpPost]
        public JsonResult Add(Category category)
        {
            JsonViewModel _jdata = new JsonViewModel();
            if (ModelState.IsValid)//模型验证通过
            {
                //父栏目
                if (category.ParentId == 0) category.ParentPath = "0";
                else
                {
                    var _parentCategory = categoryRepository.Find(category.ParentId);
                    if (_parentCategory == null) ModelState.AddModelError("ParentId", "父栏目不存在。");
                    else if (_parentCategory.Type != 0) ModelState.AddModelError("ParentId", "父栏目不是常规栏目,不能添加子栏目。");
                    else category.ParentPath = _parentCategory.ParentPath + "," + _parentCategory.CategoryId;
                }
                //根据栏目类型验证字段
                switch (category.Type)
                {
                    case 0://常规栏目
                        if (string.IsNullOrEmpty(category.Model))//模型为空
                        {
                            category.ContentView = category.LinkUrl = category.RecordUnit = category.RecordName = null;
                            category.ContentOrder = category.PageSize = null;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(category.CategoryView)) ModelState.AddModelError("CategoryView", "栏目视图不能为空。");
                            if (string.IsNullOrEmpty(category.ContentView)) ModelState.AddModelError("ContentView", "内容视图不能为空。");
                            if (category.ContentOrder == null) ModelState.AddModelError("ContentOrder", "内容排序方式不能为空。");
                            if (category.PageSize == null) ModelState.AddModelError("PageSize", "每页记录数不能为空。");
                            if (string.IsNullOrEmpty(category.RecordUnit)) ModelState.AddModelError("RecordUnit", "记录单位不能为空。");
                            if (string.IsNullOrEmpty(category.RecordName)) ModelState.AddModelError("RecordName", "记录名称不能为空。");
                            category.LinkUrl = null;
                        }
                        break;
                    case 1://单页栏目
                        if (string.IsNullOrEmpty(category.CategoryView)) ModelState.AddModelError("CategoryView", "栏目视图不能为空。");;
                        category.Model = category.ContentView = category.LinkUrl = category.RecordUnit = category.RecordName = null;
                        category.ContentOrder = category.PageSize = null;
                        break;
                    case 2:
                        if (string.IsNullOrEmpty(category.LinkUrl)) ModelState.AddModelError("LinkUrl", "链接地址不能为空。");
                        category.Model = category.CategoryView = category.ContentView = category.RecordUnit = category.RecordName =category.ContentView = null;
                        category.ContentOrder = category.PageSize = null;
                        break;
                }
                //存在逻辑验证错误
                if (!ModelState.IsValid) return Json(new JsonViewModel(ModelState));
                else
                {
                    if (categoryRepository.Add(category)) return Json(new JsonViewModel() { Success = true, Message = "添加栏目成功!" });
                    else return Json(new JsonViewModel() { Success = false, Message = "未能保存导数据库。" });
                }
            }
            //模型验证失败
            else return Json(new JsonViewModel(ModelState));
        }

image

posted @ 2013-12-02 00:15  洞庭夕照  阅读(3268)  评论(2编辑  收藏  举报