学用MVC4做网站五:5.1添加文章

五、文章

在【ArticleController】添加[UserAdd()]action

/// <summary>
        /// 添加文章
        /// </summary>
        [UserAuthorize]
        public ActionResult UserAdd()
        {
            return View(new Article() { CommonModel = new CommonModel() });
        }

右键添加模型类为Article的强类型视图UserAdd.cshtml。编辑器选用KindEditor(国货当自强)……

@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.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" />@Html.ValidationMessageFor(model => model.CommonModel.CategoryId)<br />
                                <ul id="categorytree" class="ztree comboztree"><li>222</li></ul>
                                
                            </div>
                        </dd>
                        <dd>
                            <div class="editor-label">
                                @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);
        });
        $("#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")
}

F5一下

image

再次打开【ArticleController】添加[UserAdd(Article article)action。在action上添加[ValidateInput(false)]属性停用对用户输入内容的验证。

[HttpPost]
        [UserAuthorize]
        [ValidateInput(false)]
        public ActionResult UserAdd(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)
            {
                if (articleRsy.Add(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") + "'>添加文章</a>页面,输入正确的信息后重新操作</li><li>返回<a href='" + Url.Action("UserDefault", "Article") + "'>文章管理首页</a>。</li><li>联系网站管理员</li>") };
                    return RedirectToAction("ManageError", "Prompt", _e);
                }
            }
            return View(article);
        }

action中首先检查提交过来的栏目ID对应的栏目是否存在,再次验证该栏目是否运行添加文章,然后设置发布者和模型,最后保存到数据库。

F5 浏览器中测试一下。

image

添加成功

image

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

代码见 五、文章

posted @ 2013-01-20 22:08  洞庭夕照  阅读(3915)  评论(10编辑  收藏  举报