ASP.NET MVC 实现页落网资源分享网站+充值管理+后台管理(8)之文章管理

    到这一步,我们整个项目的核心搭建已经算是完成了,接下来就是我们业务功能的实际应用,也就是表现层的设计和实现,如果你是一个项目负责人,到这一步,接下来的工作就可以交给下面的兄弟去完成了,在这里我们用文章管理来详细的讲解一下应用层的搭建、以及数据的加载和分页等。

    一、创建控制器和视图

    我们在区域BackstageModule下的Controllers文件夹中创建一个名叫ArticleMangeController的控制器,然后通过控制器添视图(Index.cshtml,Form.cshtml),并让其继承PublicController公共控制器,然后我们在ArticleMangeController控制器中创建视图中所需要的方法(数据查询、添加修改、删除),以及业务层(Com_ArticleBll.cs)的业务方法(为了规范,我们尽量把方法写在对应的业务中)。

    (1)ArticleMangeController文章控制器

using Bobo.Utilities;
using IA.Business;
using IA.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace IA.WebApp.Areas.BackstageModule.Controllers
{
    /// <summary>
    /// 文章管理控制器
    /// </summary>
        public class ArticleMangeController : PublicController<Com_Article>
        {
            //
            // GET: /BackstageModule/ArticleMange/

            /// <summary>
            /// 获取分页数据
            /// </summary>
            /// <param name="ArticleTitle"></param>
            /// <param name="jgp"></param>
            /// <returns></returns>

            public ActionResult GetTable(string ArticleTitle, string ArticleType, JqGridParam jgp)
            {
                ArticleTitle = ArticleTitle.Replace("&nbsp;", "");
                ArticleType = ArticleType.Replace("&nbsp;", "");
                Com_ArticleBll bll = new Com_ArticleBll();
                DataTable model = bll.GetTablePage(ArticleTitle, ArticleType, ref jgp);
                //构建分页数据
                var JsonData = new
                {
                    success = true,
                    pageData = jgp,
                    message = "",
                    data = model
                };
                return Content(JsonData.ToJson());
            }
            /// <summary>
            /// 提交表单
            /// </summary>
            /// <param name="entity"></param>
            /// <param name="KeyValue"></param>
            /// <returns></returns>
            [HttpPost]
            [ValidateInput(false)]

            public ActionResult SubmitFormData(Com_Article entity, string KeyValue)
            {
                HttpPostedFileBase PicFile = Request.Files["PicUrl"];
                Com_ArticleBll bll = new Com_ArticleBll();
                try
                {
                    int IsOk = 0;
                    string Message = KeyValue == "" ? "新增成功。" : "编辑成功。";
                    #region 题图处理
                    bool PicHasFile = PicFile != null && PicFile.ContentLength > 0;

                    List<string> fileType = ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageType").ToLower().Split('|').ToList();
                    string PicName = "";
                    if (PicHasFile)
                    {
                        PicName = Path.GetFileName(PicFile.FileName);
                    }
                    if (PicHasFile && !fileType.Contains(Path.GetExtension(PicName).ToLower()))
                    {
                        return Content(new JsonMessage { Code = "-1", Success = false, Message = "题图只能上传" + ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageType").ToLower() + "类型的文件!" }.ToString());
                    }
                    if (PicHasFile && CommonHelper.GetInt(SizeHelper.CountSizeNum(PicFile.ContentLength)) > CommonHelper.GetInt(ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageSize")))
                    {
                        return Content(new JsonMessage { Code = "-1", Success = false, Message = "文件大小不能超过" + ConfigHelper.GetSystemConfig("SystemConfig", "fileUploadPath", "ImageSize") + "M!" }.ToString());
                    }
                    string PicPath = "/Resource/Article/TitleImage/";
                    string FilePath = DirFileHelper.WebPathTran(PicPath);
                    DirFileHelper.CreateDirectory(FilePath);

                   
                    if (PicFile != null && PicFile.ContentLength > 0)
                    {
                        string NewFileName = CommonHelper.GetGuidNotLine() + PicName;
                        PicFile.SaveAs(FilePath + NewFileName);
                        entity.PicUrl = PicPath + NewFileName;

                    }
                    #endregion
                    if (!string.IsNullOrEmpty(KeyValue))
                    {
                        Com_Article Oldentity = bll.Factory.FindEntity(KeyValue);//获取没更新之前实体对象
                        entity.Modify(KeyValue);
                        IsOk = bll.Factory.Update(entity);
                        this.WriteLog(IsOk, entity, Oldentity, KeyValue, Message);
                    }
                    else
                    {
                        entity.Create(false);//登录功能做好改为true
                        IsOk = bll.Factory.Insert(entity);
                        this.WriteLog(IsOk, entity, null, KeyValue, Message);
                    }
                    return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());
                }
                catch (Exception ex)
                {
                    this.WriteLog(-1, entity, null, KeyValue, "操作失败:" + ex.Message);
                    return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
                }
            }
            /// <summary>
            /// 假删方法
            /// </summary>
            /// <param name="KeyValue"></param>
            /// <returns></returns>
            public ActionResult DeleteOther(string KeyValue)
            {
                Com_ArticleBll bll = new Com_ArticleBll();

                try
                {
                    int IsOk = 1;
                    string Message = "删除成功";
                    if (!string.IsNullOrEmpty(KeyValue))
                    {
                        string[] array = KeyValue.Split(',');
                        foreach (var item in array)
                        {
                            Com_Article Oldentity = bll.Factory.FindEntity(item);//获取没更新之前实体对象
                            Oldentity.DeleteMark = 1;
                            Oldentity.Modify(item, false);//登录功能做好改为true
                            IsOk = bll.Factory.Update(Oldentity);
                            this.WriteLog(IsOk, Oldentity, Oldentity, item, Message);
                        }
                    }
                    else
                    {
                        Message = "删除失败";
                        IsOk = 1;

                    }
                    return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());
                }
                catch (Exception ex)
                {
                    this.WriteLog(-1, null, null, KeyValue, "操作失败:" + ex.Message);
                    return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
                }

            }
            /// <summary>
            /// 文章发布
            /// </summary>
            /// <param name="KeyValue"></param>
            /// <returns></returns>
            public ActionResult PutArticle(string KeyValue, int State)
            {
                Com_ArticleBll bll = new Com_ArticleBll();

                try
                {
                    int IsOk = 1;
                    string Message = "操作成功";
                    if (!string.IsNullOrEmpty(KeyValue))
                    {
                        string[] array = KeyValue.Split(',');
                        foreach (var item in array)
                        {
                            Com_Article Oldentity = bll.Factory.FindEntity(item);//获取没更新之前实体对象
                            Oldentity.PutTime = DateTime.Now;
                            Oldentity.State = State;
                            Oldentity.Modify(item, false);//登录功能做好改为true
                            IsOk = bll.Factory.Update(Oldentity);
                            this.WriteLog(IsOk, Oldentity, Oldentity, item, Message);
                        }
                    }
                    else
                    {
                        Message = "操作失败";
                        IsOk = 0;
                    }
                    return Content(new JsonMessage { Success = true, Code = IsOk.ToString(), Message = Message }.ToString());
                }
                catch (Exception ex)
                {
                    this.WriteLog(-1, null, null, KeyValue, "操作失败:" + ex.Message);
                    return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
                }

            }
        }
    }

(2)Com_ArticleBll.cs 业务方法

using Bobo.DataAccess;
using Bobo.Repository;
using Bobo.Utilities;
using IA.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IA.Business
{
    // <summary> 
    /// 文章信息表 
    /// <author> 
    ///     <name>YHB</name> 
    ///      <date>2018.10.18</date> 
    /// </author> 
    /// </summary> 
    public class Com_ArticleBll : RepositoryFactory<Com_Article>
    {
        /// <summary>
        /// 获取文章数据
        /// </summary>
        /// <param name="ArticleTitle"></param>
        /// <param name="jgp"></param>
        /// <returns></returns>
        public DataTable GetTablePage(string ArticleTitle, string ArticleType, ref JqGridParam jgp)
        {
            StringBuilder whereSql = new StringBuilder();
            List<DbParameter> param = new List<DbParameter>();

            whereSql.Append(@" AND DeleteMark<>1");
            if (!StringHelper.IsNullOrEmpty(ArticleTitle))
            {
                whereSql.Append(@" AND ArticleTitle LIKE @ArticleTitle");
                param.Add(DbFactory.CreateDbParameter("@ArticleTitle", '%' + ArticleTitle + '%'));
            }
            if (!StringHelper.IsNullOrEmpty(ArticleType))
            {
                whereSql.Append(@" AND ArticleType=@ArticleType");
                param.Add(DbFactory.CreateDbParameter("@ArticleType", ArticleType));
            }
            return Factory.FindTablePage(whereSql.ToString(), param.ToArray(), ref jgp);
        }
       

    }
}

(3)在实现视图之前,我们需要在区域下的Shared中创建一个分部视图_PartialNav.cshtml存放左边菜单

<div class="center-nav L font-yahei">
    <div class="center-nav-title">功能导航</div>
   
    <div class="center-nav-item"><a href="/BackstageModule/JournalMange/Index" class="scgl">素材管理</a></div>
    <div class="center-nav-item"><a href="/BackstageModule/PayForMange/Index" class="zfgl">支付管理</a></div>
    <div class="center-nav-item"><a href="/BackstageModule/BannerMange/Index" class="gggl">广告管理</a></div>
    <div class="center-nav-item"><a href="/BackstageModule/ArticleMange/Index" class="hydt">资讯管理</a></div>
</div>

(4)Index.cshtml视图中的代码:

@{
    ViewBag.Title = "管理后台 - 资讯";
    Layout = "~/Views/Shared/_LayoutMange.cshtml";
}
<style>
    html {
        background-color: #f3f4f4;
    }

    .w_header .header-nav .nav-item li a.wzgl {
        border-bottom: 2px solid #2D81E0;
        background-color: #E8F4FF;
        color: #2D81E0;
        font-weight: bold;
    }
</style>
<div class="w_center clear mAuto">
    @Html.Partial("_PartialNav")
    <div class="center-main R">
        <h2 class="center-main-title font-yahei">
            <span>资讯管理&nbsp; /</span>&nbsp;&nbsp;<i>management news</i>
        </h2>

        <div class="center-main-box">
            <div class="toolbarBox clear">
                <div id="searchForm" class="L searchForm">
                    <span class="seachTit">文章标题:</span>
                    <input type="text" id="ArticleTitle" class="seachText" value="" />
                    <input type="text" id="ArticleType" class="seachText" value="" />
                    <a id="searchBtn" class="searchBtn" href="javascript:;" title="搜索"></a>
                </div>

                <div class="toolbar R">
                    <input type="button" value="添加" class="mainBtn addBtn greenBtn" onclick="showAdd()" />
                    <input type="button" value="发布" class="mainBtn putBtn yellowBtn" onclick="putBtn(1)" />
                    <input type="button" value="取消发布" class="mainBtn putBtn blueBtn sxLenth" onclick="putBtn(0)" />
                    <input type="button" value="删除" class="mainBtn delBtn blueBtn" onclick="delBtn()" />
                </div>
            </div>
            <table class="dataTable" style="width:100%;">
                <thead>
                    <tr>
                        <td style="width:10%;" class="remElem"><input type="checkbox" class="ckbAll " />选定</td>
                        <td style="width:40%;" class="tbTit">文章类型</td>
                        <td style="width:40%;" class="tbTit">文章标题</td>
                        <td style="width:15%;" class="remElem">推荐</td>
                        <td style="width:15%;">发布时间</td>
                        <td style="width:15%;">操作</td>
                    </tr>
                </thead>
                <tbody id="dataBody"></tbody>
            </table>
            <div id="listPage" class="m_pageBar com_pageBar" style="padding:0 30px;"></div>
        </div>
    </div>
</div>




@*分页数据模版*@
<script id="tempBody" type="text/template">
    {#each data as item}
    <tr>
        <td style="text-align: center;"><input type="checkbox" class="ckb" data-id="!{item.ArticleID}" onclick="change(this)" /></td>
        <td>!{item.ArticleType}</td>
        <td><a href="/BackstageModule/ArticleMange/Form?KeyValue=!{item.ArticleID}">!{item.ArticleTitle}</a> </td>
        {#if item.OptionSet == 1}
        <td style="text-align:center;"><img src="/Content/Images/slice/optionIco.png" width="16" height="16" title="推荐" /></td>
        {#else}
        <td style="text-align:center;"></td>
        {#/if}
        {#if item.State==1}
        <td style="text-align:center;">!{formatDate(item.PutTime, "yyyy-MM-dd")}</td>
        {#else}
        <td style="text-align:center;">未发布</td>
        {#/if}
        <td style="text-align:center;"><a href="/BackstageModule/ArticleMange/Form?KeyValue=!{item.ArticleID}" class="tbBtn tbEdit">编辑</a></td>
    </tr>
    {#/each}
</script>

@section scripts{
    <script type="text/javascript">
        var KeyValue = "";

        $(function () {
            juicer.register('formatDate', formatDate);
            getPageData();
            searchEvent();
        });
        //初始化分页函数
        function getPageData() {
            var param = {
                rows: 10,
                url: "/BackstageModule/ArticleMange/GetTable",
                sidx: "CreateDate",
                sord: "DESC",
                searchForm: "#searchForm",
                infoPanel: '#dataBody',
                barPanel: '#listPage',
                template: '#tempBody',
                callback: handleSuccess
            }
            Pager.init(param);

        }
        //查询按钮绑定事件
        function searchEvent() {
            $("#searchBtn").on("click", function () {
                getPageData();
            });
        }

        //添加弹窗
        function showAdd() {
            window.location = "/BackstageModule/ArticleMange/Form";
        }

        //删除
        function delBtn() {
            var allVal = "";
            $(".dataTable tbody tr").find(".ckb").each(function () {
                var ckb = $(this);
                var ckbVal = ckb.prop("checked");
                var dataId = ckb.attr("data-id");
                if (ckbVal == "checked" || ckbVal == true) {
                    allVal += (allVal == "" ? dataId : "," + dataId);
                }
            });

            if (allVal == "") {
                layer.alert("您没有选中任何项,请选中后再进行操作!", { icon: 0 });
                return false;
            }
            layer.confirm("是否删除这" + allVal.split(",").length + "条数据?", { icon: 0 }, function () {
                AjaxJson("/BackstageModule/ArticleMange/DeleteOther", { KeyValue: allVal }, function (data) {
                    layer.msg(data.Message, { icon: data.Code, time: 1000 }, function () {
                        Pager.reload();
                    });
                });
            });

        }
        //发布
        function putBtn(num) {
            var allVal = "";
            $(".dataTable tbody tr").find(".ckb").each(function () {
                var ckb = $(this);
                var ckbVal = ckb.prop("checked");
                var dataId = ckb.attr("data-id");
                if (ckbVal == "checked" || ckbVal == true) {
                    allVal += (allVal == "" ? dataId : "," + dataId);
                }
            });

            if (allVal == "") {
                layer.alert("您没有选中任何项,请选中后再进行操作!", { icon: 0 });
                return false;
            }
            AjaxJson("/BackstageModule/ArticleMange/PutArticle", { KeyValue: allVal, State: num }, function (data) {
                layer.msg(data.Message, { icon: data.Code, time: 1000 }, function () {
                    Pager.reload();
                });
            });
        }
        //分页数据加载后绑定的函数
        function handleSuccess() {
            checkAll();
        }
        //全选(包括)
        function checkAll() {
            //全选按钮
            $(".dataTable thead").find(".ckbAll").change(function () {
                var chkAll = $(this);
                var chkVal = chkAll.prop("checked");
                if (chkVal == "checked" || chkVal == true) {
                    $(".dataTable tbody tr").each(function () {
                        var chk = $(this).find(":checkbox");
                        chk.prop("checked", "checked");
                    });
                }
                else {
                    $(".dataTable tbody tr").each(function () {
                        var chk = $(this).find(":checkbox");
                        chk.removeAttr("checked");
                    });
                }
            });


        }
    </script>

}

在上面的代码中,我们引用了前面创建好的_LayoutMange.cshtml头尾布局页,还用到了juicer轻量级的模板加载数据以及弹窗,分页操作是自己写的一个m_pager.js方法配合着juicer使用,下面我们看具体代码:

//刷新表格参数
var reloadParam = null;
//是否往前退页;默认为退,传入false时不退页
var isPrevPage = true;

var Pager = function(){
    return {
        init: function(param){
            getList(param);
        },
        reload: function (IsPrevPage) {
            isPrevPage = IsPrevPage;
            reloadPage(reloadParam);
        }
    }
}();

/*初始化需要的参数
param = {
    page:目标页码(默认:0或1均可),
    rows:每页显示条数(默认:15),
    url:请求地址,
    sidx:排序字段
    sord:排序类型;
    onePageShow:数据只有一页时是否显示分页(默认不显示)
    searchForm:查询条件所在容器
    infoPanel:信息回填容器,
    barPanel:分页条回填容器,
    template:信息模板容器,
    callback:查询到分页数据后执行的回掉函数
    noDataCallBack:未查询到分页数据执行的回掉函数
}
*/
function getList(json) {//获取评论列表
    var json = json || {};

    var target = json.page || 1,                //请求页码
        aver = json.rows || 15,                 //每页显示数量,默认15
        sidx = json.sidx,                       //排序字段名
        sord = json.sord,                       //排序类型ASC DESC
        url = json.url,                         //请求URL
        onePageShow = json.onePageShow || false,//数据只有一页时是否显示分页(默认不显示)
        searchForm = json.searchForm,           //查询条件所在容器
        infoPanel = json.infoPanel,             //回填数据容器
        barPanel = json.barPanel,               //分页条容器
        template = json.template,               //模版
        callback = json.callback,               //加载数据成功后执行的回调函数
        noDataCallback = json.noDataCallback;   //加载数据为空时的回调函数

    //从初始化参数中构建分页请求参数,包括所有JqGridParam参数和查询条件
    var requestParam = searchForm ? GetWebControls(searchForm) : {};
    requestParam.page = target;
    requestParam.rows = aver;
    requestParam.sidx = sidx;
    requestParam.sord = sord;
    var load = layer.msg('正在加载页面数据…', { icon: 16, shade: 0.05, time: 0, area:"210px" });
    window.setTimeout(function () {
        $.post(url, requestParam, function (d) {
            if (d.success) {
                if (typeof d.data == 'undefined' || d.data.length == 0) {
                    var width = $(infoPanel).width() <= 0 ? $(infoPanel).parent().width() : $(infoPanel).width();
                    $(infoPanel).html('<h4 class="noInfo" style="width:' + width + 'px">暂无信息</h4>');
                    $(barPanel).hide();
                    noDataCallback ? noDataCallback() : null;
                } else {
                    $(barPanel).show();
                    $(infoPanel).html(juicer($(template).html(), d));
                    callback ? callback(d) : null;
                }
                getPage(json, d.pageData, d.data.length, barPanel, getList);
            } else {
                layer.alert(d.pageData);  
            }
            layer.close(load);
        }, "json");
    }, 500);    
}

/*分页S*/

/*
pageParam 分页参数json
pageParam = {
    "records":int,       总数据条数    int
    "rows":int,          每页显示条数  int
    "page":int,          当前页索引(从0开始)
    "total":int,         查询结果的记录总数
    "dataLength":int     当前页所包含的记录数
}
*/
function getPage(json, pageParam, dataLength, panel, fn) {
    var pageNum = Math.ceil(pageParam.records / pageParam.rows);
    var barHtml = "";
    var tempHtml = "";
    if (pageNum <= 1) {
        if (json.onePageShow) {
            barHtml = '<div class="L clearfix">\
                        <a href="javascript:;" class="first aElem"><i class="icon_first"></i>首页</a>\
                        <a href="javascript:;" class="prev aElem"><i class="icon_pre"></i>上一页</a>'
                        + tempHtml +
                        '<a href="javascript:;" class="next aElem"><i class="icon_next"></i>下一页</a>\
                        <a href="javascript:;" class="last aElem"><i class="icon_last"></i>尾页</a>\
                    </div>\
                    <p class="page_info R">共 ' + pageNum + ' 页 ' + pageParam.records + ' 条记录 当前显示 第( <em>' + (pageParam.page) + '</em> )页</p>';
        }
    }
    else if (pageNum <= 8) {
        for (var i = 1; i <= pageNum; i++) {
            if (i == pageParam.page) {
                tempHtml += '<a href="javascript:;" class="pageBtn active">' + i + '</a>';
            } else {
                tempHtml += '<a href="javascript:;" class="pageBtn">' + i + '</a>'
            }
        }
        barHtml = '<div class="L clearfix">\
                        <a href="javascript:;" class="first aElem"><i class="icon_first"></i>首页</a>\
                        <a href="javascript:;" class="prev aElem"><i class="icon_pre"></i>上一页</a>'
                        + tempHtml +
                        '<a href="javascript:;" class="next aElem"><i class="icon_next"></i>下一页</a>\
                        <a href="javascript:;" class="last aElem"><i class="icon_last"></i>尾页</a>\
                    </div>\
                    <p class="page_info R">共 ' + pageNum + ' 页 ' + pageParam.records + ' 条记录 当前显示 第( <em>' + (pageParam.page) + '</em> )页</p>';
    } else {
        var start = 0;
        var end = 0;
        if (pageNum <= 8) {
            start = 1;
            end = pageNum;
        } else {
            if (pageParam.page <= 1) {
                start = 1;
                end = 8;
            } else if (pageParam.page + 6 <= pageNum) {
                start = pageParam.page - 1;
                end = pageParam.page + 6;
            } else {
                start = pageNum - 6;
                end = pageNum;
            }
        }
        for (var i = start; i <= end; i++) {
            if (i == pageParam.page) {
                tempHtml += '<a href="javascript:;" class="pageBtn active">' + i + '</a>';
            } else {
                tempHtml += '<a href="javascript:;" class="pageBtn">' + i + '</a>'
            }
        }
        barHtml = '<div class="L p_clearfix">\
                        <a href="javascript:;" class="first aElem"><i class="icon_first"></i>首页</a>\
                        <a href="javascript:;" class="prev aElem"><i class="icon_pre"></i>上一页</a>'
                        + tempHtml +
                        '<a href="javascript:;" class="next aElem"><i class="icon_next"></i>下一页</a>\
                        <a href="javascript:;" class="last aElem"><i class="icon_last"></i>尾页</a>\
                    </div>\
                    <p class="page_info R">共 ' + pageNum + ' 页 ' + pageParam.records + ' 条记录 当前显示第(<em>' + (pageParam.page) + '</em>)页</p>';
    }
    if (!$(panel).hasClass('.m_pageBar')) {
        $(panel).addClass('m_pageBar');
    }
    $(panel).html(barHtml);
  
   
    //waterfall(".center-ul", ".center-ul-li");
    $("a", panel).click(function () {
        var now = pageParam.page;
        var target = pageParam.page;
        if ($(this).text() == (now).toString()) {
            return false;
        } else if ($(this).hasClass("first")) {
            if (now == 1) {
                return false;
            } else {
                target = 1;
            }
        } else if ($(this).hasClass("last")) {
            if (now == pageParam.total) {
                return false;
            } else {
                target = pageParam.total;
            }
        } else if ($(this).hasClass("prev")) {
            if (now == 1) {
                return false;
            } else {
                target = now - 1;
            }
        } else if ($(this).hasClass("next")) {
            if (now == pageNum) {
                return false;
            } else {
                target = now + 1;
            }
        } else {
            var text = parseInt($(this).text());
            target = text;
        }
        json.page = target;
        fn(json);
        return false;
    });
    reloadParam = json;
    //当前如果是最后一页,并且只有一条记录时,重载参数会指向前一页
    //console.info("zuihou" + (json.page == pageNum));
    //console.info("jilu" + (dataLength == 1));
    if (json.page == pageNum && dataLength == 1) {
        isPrevPage ? null : reloadParam.page -= 1;
    }
}
/*分页E*/

/*重载当前页*/
function reloadPage() {
    getList(reloadParam);
}
/*重载当前页*/

(5)Form.cshtml视图实现,在这个视图中我们主要用到富文本编辑器,对于该编辑器的一些设置(比如代码高亮等),在前篇文章中我们已经详细讲到,同时这个用到了的js方法和验证都在我们之前的前端文件中。下面看看改视图中的代码:

@{
    ViewBag.Title = "文章管理 - 添加/编辑";
    Layout = "~/Views/Shared/_LayoutMange.cshtml";
}

<style>
    .w_header .header-nav .nav-item li a.wzgl {
        border-bottom: 2px solid #2D81E0;
        background-color: #E8F4FF;
        color: #2D81E0;
        font-weight: bold;
    }
</style>
<div class="w_center clear mAuto center-all">
    <div class="center-map-nav font-yahei">
        <div class="map-nav-tit L"><i><img src="~/Content/Images/slice/titIco.png" width="9" height="18" /></i><span class="map-nav-name">行业资讯</span><span>-添加/编辑</span></div>
        <div class="map-nav-btn R">
            <input type="button" value="保存" class="mainBtn addBtn greenBtn" onclick="AcceptClick(0)" />
            @*<input type="button" value="发布" class="putBtn blueBtn" onclick="AcceptClick(1)" />*@
            <input type="button" value="返回列表" class="mainBtn blueBtn " onclick="GoBack()" />
        </div>
    </div>
    <form id="form1" class="form" action="/BackstageModule/ArticleMange/SubmitFormData" method="post" enctype="multipart/form-data" style="margin: 1px">
        <input type="hidden" id="KeyValue" name="KeyValue" />
        @*<input type="hidden" id="ArticleType" name="ArticleType" />*@
        <input type="hidden" id="State" name="State" value="0" />
        <table class="form-table  font-yahei">
            <tr>
                <td colspan="4" class="center-tip">
                    <p>* 格式规范:正文使用宋体14px,1.5倍行距,小标题文字使用宋体加粗,大于等于14px</p>
                    <p>* 附件上传:点击编辑器工具栏 → 回形针&nbsp;<img src="~/Content/Images/slice/attach.png" width="20" height="18" />&nbsp;图标</p>
                </td>
            </tr>
            <tr>
                <td class="table-title">标题</td>
                <td class="table-text"><input type="text" class="txt required" name="ArticleTitle" id="ArticleTitle" datacol="yes" err="标题" checkexpession="NotNull" /></td>
                <td class="table-title">类型</td>
                <td class="table-text">
                    <select id="ArticleType" name="ArticleType" class="txt">
                        <option value="zw">杂文</option>
                        <option value="tx">图像</option>
                        <option value="yx">影像</option>
                        <option value="yy">音乐</option>
                        <option value="qg">情感</option>
                        <option value="lx">旅行</option>
                    </select>
                </td>
            </tr>
            <tr class="remveAB">
                <td class="table-title">题图<span style="color:#999;">(用于首页轮播)</span></td>
                <td class="table-text">
                    <div class="PicBox">
                        <input class="file PicUrl" type="file" name="PicUrl" value="" onchange="SetFileVal($(this))" />
                    </div>
                    <input type="text" class="url1 img-url" readonly="readonly" style="display:none;" />
                    <input type="text" class="url2 img-url" name="PicUrl" id="PicUrl" readonly="readonly" />
                </td>
                <td class="table-title">选项</td>
                <td class="table-text">
                    <input type="hidden" name="OptionSet" id="OptionSet" value="0" />
                    <input type="checkbox" class="CheckOptionSet" onchange="CheckOptionSet($(this))" /><span>推荐</span><span style="color:#999;">(用于首页轮播)</span>
                </td>
            </tr>
            <tr>
                <td class="table-title">文章来源</td>
                <td class="table-text"><input type="text" class="txt" name="Source" id="Source" /></td>
                <td class="table-title">发布时间</td>
                <td class="table-text"><input type="text" class="txt Wdate" name="PutTime" id="PutTime" onfocus="WdatePicker()" datacol="yes" err="发布时间" /></td>

            </tr>
            
        </table>
        <div>
            <textarea id="ArticleContent" name="ArticleContent" maxlength=2147483647 class="txtArea" datacol="yes" err="文章内容" checkexpession="NotNull" style="width:99.9%;"></textarea>
        </div>
    </form>
</div>

@section scripts{
    <script src="~/Content/Scripts/ueditor/ueditor.config.js"></script>
    <script src="~/Content/Scripts/ueditor/ueditor.all.js"></script>
    <script src="~/Content/Scripts/ueditor/lang/zh-cn/zh-cn.js"></script>
    <script src="~/Content/Scripts/ueditor/prettify.js"></script>
    <script type="text/javascript">
        prettyPrint(); //代码高亮
        var KeyValue = GetQuery('KeyValue').replace("null", "");//关于我们无内容时为null
        var ab = GetQuery('ab');
        $(function () {

            var ue = UE.getEditor('ArticleContent', { autoFloatEnabled: false, autoHeightEnabled: false });
            ue.addListener('ready', function (editor) {
                var height = $(window).height(),
                    tabHeight = $(".form-table").outerHeight();
                headHeight = $(".w_header").outerHeight();
                footHeight = $(".w_footer").outerHeight();
                editToolHeight = $("#edui1_toolbarbox").outerHeight(),
                editBottomHeight = $("#edui1_bottombar").outerHeight(),
                editHeight = 300;

                ue.setHeight(editHeight);

                InitWebPage(ue);
            });

        });
        //初始化数据
        function InitWebPage(ue) {
            if (!!KeyValue) {
                $("#KeyValue").val(KeyValue);
                InitControl(ue);
            }

        }
        //文件域选择设置
        function SetFileVal(elem) {
            if (!!elem.val()) {
                $(".url1").val(elem.val()).show();
                $(".url2").hide();
            }
            else {
                $(".url1").show();
                $(".url2").hide();
            }

        }
        //选项推荐
        function CheckOptionSet(elem) {
            var elemVal = elem.prop("checked");
            if (elemVal == "checked" || elemVal == true) {
                $("#OptionSet").val(1);
            }
            else {
                $("#OptionSet").val(0);
            }
        }
        //得到一个对象实体
        function InitControl(ue) {
            AjaxJson("/BackstageModule/ArticleMange/SetForm", { KeyValue: KeyValue }, function (data) {
                data.PutTime = formatDate(data.PutTime, "yyyy-MM-dd")
                SetWebControls(data, "#form1");
                if (!!data.ArticleContent) {
                    ue.setContent(data.ArticleContent, false);
                }
                if (data.OptionSet == 1) {
                    $(".CheckOptionSet").attr("checked", "checked");
                }
            });
        }
        //保存按钮
        function AcceptClick(num) {
            if (!!KeyValue && num != 0) {
                $("#State").val(num);
            }
            //if (num == 1) {
            //    $("#PutTime").attr("checkexpession", "NotNull");
            //}
            //else {
            //    $("#PutTime").removeAttr("checkexpession");
            //}
            if (!CheckDataValid('#form1', true)) {
                return false;
            }
            //提交表单
            $("#form1").ajaxSubmit({
                dataType: "json",
                beforeSubmit: function () {
                    layer.msg('正在提交信息,请稍后…', { icon: 16, shade: 0.2, time: 0 });
                },
                success: function (data) {
                    if (data.Success) {
                        layer.closeAll();
                        if (!!ab) {
                            window.location = "/BackstageModule/About/Index";
                        }
                        else {
                            window.location = "/BackstageModule/ArticleMange/Index";
                        }
                    }
                    else {
                        layer.alert(data.Message, { icon: data.Code });
                    }
                }
            });
        }
        //返回列表
        function GoBack() {
            if (!!ab) {
                window.location = "/BackstageModule/About/Index";
            }
            else {
                window.location = "/BackstageModule/ArticleMange/Index";
            }
        }
    </script>

}

到这一步,我们一个文章管理的功能模块就完成啦,下面看看具体效果图:

FORM页面(添加修改)

文章管理 - 添加_编辑.png
index效果图:
文章管理 - 添加_编辑.png

管理后台 - 资讯.png


posted @ 2018-11-13 14:24  落日知暮  阅读(257)  评论(0编辑  收藏  举报
作者:boyzi007 出处:http://www.cnblogs.com/boyzi/ QQ:470797533 QQ交流群:364307742 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。