学用MVC4做网站五:5.3修改文章

修改文章是网站必不可少的内容,在我的文章里,文章列表后面操作栏有【修改】链接,点击调转到[UserEdit]Action,今天来实现这个Action。

image

还是打开【ArticleController】,添加[UserEdit(int id)]Action这里的id指文章Id。

/// <summary>
        /// 修改文章
        /// </summary>
        /// <param name="id">文章id</param>
        [UserAuthorize]
        public ActionResult UserEdit(int id)
        {
            return View(articleRsy.Find(id));
        }
右键添加强类型视图,视图与添加文章类似
@model Ninesky.Models.Article

@{
    ViewBag.Title = "修改文章";
    Layout = "~/Views/Shared/_User.cshtml";
}

<div class="workspace">
    <div class="inside">
        <div class="notebar">
            <img alt="" src="~/Content/Default/User/Images/Icon/Article_16.png" />您现在的位置: 修改文章
        </div>
        <div>

            @using (Html.BeginForm())
            {
                @Html.ValidationSummary(true)
                <div class="formset">
                    <dl>
                        <dt>修改文章</dt>
                        <dd>
                            <div class="editor-label">
                                @Html.HiddenFor(model => model.CommonModelId)
                                @Html.HiddenFor(model => model.CommonModel.CommonModelId)
                                @Html.LabelFor(model => model.CommonModel.CategoryId) (必填) @Html.DisplayDescriptionFor(model => model.CommonModel.CategoryId)
                            </div>
                            <div class="editor-field">
                                @Html.HiddenFor(model => model.CommonModel.CategoryId)
                                <input type="text" class = "combotree" id="CommonModel_CategoryId_Text" value="@Model.CommonModel.Category.Name" />@Html.ValidationMessageFor(model => model.CommonModel.CategoryId)<br />
                                <ul id="categorytree" class="ztree comboztree"></ul>
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.HiddenFor(model => model.ArticleId)
                                @Html.LabelFor(model => model.CommonModel.Title) (必填) @Html.DisplayDescriptionFor(model => model.CommonModel.Title)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.CommonModel.Title)
                                @Html.ValidationMessageFor(model => model.CommonModel.Title)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.Source)@Html.DisplayDescriptionFor(model => model.Source)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.Source)
                                @Html.ValidationMessageFor(model => model.Source)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.Intro)@Html.DisplayDescriptionFor(model => model.Intro)
                            </div>
                            <div class="editor-field">
                                @Html.TextAreaFor(model => model.Intro, new { @class = "Intro" })
                                @Html.ValidationMessageFor(model => model.Intro)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.CommonModel.PicUrl)@Html.DisplayDescriptionFor(model => model.CommonModel.PicUrl)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.CommonModel.PicUrl)
                                @Html.ValidationMessageFor(model => model.CommonModel.PicUrl)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.CommonModel.Status)@Html.DisplayDescriptionFor(model => model.CommonModel.Status)
                            </div>
                            <div class="editor-field">
                                @Html.DropDownListFor(model => model.CommonModel.Status,Ninesky.Models.CommonModel.ContentStatus)
                                @Html.ValidationMessageFor(model => model.CommonModel.Status)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.CommonModel.ReleaseDate) (必填) @Html.DisplayDescriptionFor(model => model.CommonModel.ReleaseDate)
                            </div>
                            <div class="editor-field">
                                @Html.TextBoxFor(model => model.CommonModel.ReleaseDate, new { @class = "datepicker", type = "datetime" })
                                @Html.ValidationMessageFor(model => model.CommonModel.ReleaseDate)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.Content) (必填) @Html.DisplayDescriptionFor(model => model.Content)
                            </div>
                            <div class="editor-field">
                                @Html.TextAreaFor(model => model.Content, new { @class = "content" })
                                @Html.ValidationMessageFor(model => model.Content)
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                            </div>
                            <div class="editor-field">
                                <input type="submit" value="确定" />
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                            </div>
                            <div class="editor-field">
                            </div>
                        </dd>
                    </dl>
                </div>
            }
        </div>
    </div>
</div>
<div class="left">@Html.Partial("PartialUserNavMenus")<br /></div>
<div class="clear"></div>
<script type="text/javascript">
    KindEditor.ready(function (K) {
        K.create('#Content');
    });
    var setting = {
        view: { selectedMulti: false },
        callback: {
            onClick: zTreeOnClick
        }
    };
    $(document).ready(function () {
        $.post("@Url.Action("JsonUserGeneralTree", "Category")", { model: "Article" }, function (data) {
            var zTree = $.fn.zTree.init($("#categorytree"), setting, data);
            zTree.expandAll(true);
            var node = zTree.getNodeByParam("id", $("#CommonModel_CategoryId").val(), null);
            zTree.selectNode(node);
        });
        $("#CommonModel_CategoryId_Text").click(function () {
            $("#categorytree").show();
        });
    });
    function zTreeOnClick(event, treeId, treeNode) {
        if (treeNode.iconSkin == "canadd") {
            $("#CommonModel_CategoryId").val(treeNode.id);
            $("#CommonModel_CategoryId_Text").val(treeNode.name);
            $("#categorytree").hide();
        }
        else {
            alert("该栏目不能文章");
        }
    };
    $("#CommonModel_ReleaseDate").datepicker({
    })
    $("input[type='submit']").button();
    
</script>
@section Scripts {
    @Styles.Render("~/ZtreeCss")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Ztree")
    @Scripts.Render("~/bundles/kindeditor")
}

修改文章处理action UserEdit(Article article)

[HttpPost]
        [UserAuthorize]
        [ValidateInput(false)]
        public ActionResult UserEdit(Article article)
        {
            //验证栏目
            CategoryRepository _categoryRsy = new CategoryRepository();
            var _category = _categoryRsy.Find(article.CommonModel.CategoryId);
            if (_category == null) ModelState.AddModelError("CommonModel.CategoryId", "栏目不存在");
            if (_category.Model != "Article") ModelState.AddModelError("CommonModel.CategoryId", "该栏目不能添加文章!");
            article.CommonModel.Inputer = UserController.UserName;
            ModelState.Remove("CommonModel.Inputer");
            article.CommonModel.Model = "Article";
            ModelState.Remove("CommonModel.Model");
            if (ModelState.IsValid)
            {
                var _article = articleRsy.Find(article.ArticleId);
                if (_article == null)//文章不存在
                {
                    Error _e = new Error { Title = "文章不存在", Details = "查询不到ArticleId为【" + article.ArticleId.ToString() + "】的文章", Cause = "文章已被删除或向服务器提交文章时数据丢失", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("UserOwn", "Article") + "'>我的文章</a>重新操作</li><li>返回<a href='" + Url.Action("UserDefault", "Article") + "'>文章管理首页</a>。</li><li>联系网站管理员</li>") };
                    return RedirectToAction("ManageError", "Prompt", _e);
                }
                if (_article.CommonModel.Title != article.CommonModel.Title) _article.CommonModel.Title = article.CommonModel.Title;
                if (_article.CommonModel.CategoryId != article.CommonModel.CategoryId) _article.CommonModel.CategoryId = article.CommonModel.CategoryId;
                if (article.CommonModel.ReleaseDate != null) _article.CommonModel.ReleaseDate = article.CommonModel.ReleaseDate;
                if (article.CommonModel.Status != _article.CommonModel.Status) _article.CommonModel.Status = article.CommonModel.Status;
                if (article.CommonModel.PicUrl != null) _article.CommonModel.PicUrl = article.CommonModel.PicUrl;
                if (article.CommonModel.CommentStatus != _article.CommonModel.CommentStatus) _article.CommonModel.CommentStatus = article.CommonModel.CommentStatus;
                if (article.Source != null) _article.Source = article.Source;
                if (article.Author != null) _article.Author = article.Author;
                if (article.Intro != null) _article.Intro = article.Intro;
                _article.Content = article.Content;
                if (articleRsy.Update(_article))
                {

                    Notice _n = new Notice { Title = "修改文章成功", Details = "您已经成功修改了[" + article.CommonModel.Title + "]文章!", DwellTime = 5, NavigationName = "我的文章", NavigationUrl = Url.Action("UserOwn", "Article") };
                    return RedirectToAction("UserNotice", "Prompt", _n);
                }
                else
                {
                    Error _e = new Error { Title = "修改文章失败", Details = "在修改文章时,未能保存到数据库", Cause = "系统错误", Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("UserAdd", "Article", new { id = article.ArticleId }) + "'>修改文章</a>页面,输入正确的信息后重新操作</li><li>返回<a href='" + Url.Action("UserDefault", "Article") + "'>文章管理首页</a>。</li><li>联系网站管理员</li>") };
                    return RedirectToAction("ManageError", "Prompt", _e);
                }
            }
            return View(article);
        }

这个action也是先验证栏目是否存在,且能添加文章。呵呵,跟添加文章的基本类似。

按F5 浏览器修改篇文章看,能够修改,ok!

===========================

代码见:学用MVC4做网站五:文章

===========================

1月26日修改:

今天仔细看的时候发现一个问题。在“我的文章”修改链接代码为:@Html.ActionLink("修改","UserEdit",new {id = item.CommonModelId}),这里的id是公共模型的id,再看看ActionResult UserEdit(int id)里面的代码,文章是articleRsy.Find(id))查询返回的。转到定义看看一下代码。

/// <summary>
        /// 查找文章
        /// </summary>
        /// <param name="Id">文章id</param>
        /// <returns></returns>
        public override Article Find(int Id)
        {
            return dbContext.Articles.AsNoTracking().Include("CommonModel").SingleOrDefault(a => a.ArticleId == Id);
        }

这里的id是文章id。所以是用驴唇对了马嘴哭泣的脸.... ....

怎么改正呢?既然ActionResult UserEdit(int id)的id指的是公共模型的id,那就写个根据公共模型id查找文章的函数FindByCommonModelId(int commonModelId)就行了。

在ArticleRepository中添加FindByCommonModelId(int commonModelId)函数。

/// <summary>
        /// 根据公共模型id查找文章
        /// </summary>
        /// <param name="commonModelId">公共模型Id</param>
        /// <returns>文章</returns>
        public Article FindByCommonModelId(int commonModelId)
        {
            return dbContext.Articles.AsNoTracking().Include("CommonModel").SingleOrDefault(a => a.CommonModelId == commonModelId);
        }

将UserEdit(int id)中的return View(articleRsy.Find(id))改为return View(articleRsy.FindByCommonModelId(id))

/// <summary>
        /// 修改文章
        /// </summary>
        /// <param name="id">公共模型id</param>
        [UserAuthorize]
        public ActionResult UserEdit(int id)
        {

            return View(articleRsy.FindByCommonModelId(id));
        }
完工!
原文地址:https://www.cnblogs.com/mzwhj/p/2874757.html