如何 return 回到包含 renderpartial 的视图

How to return back to View that contain renderpartial

我正在创建简单的博客,在我的文章中我有 'comment' 部分功能。我可以将数据传递给控制器​​并成功保存数据,但是当 return 返回包含 'Comment'.

的文章视图时发生错误

这是我的Article.cshtml页面:

@model SimpleBlog.Post
 <p class="lead" style="text-align:justify; word-wrap:break-word">
        @Html.Raw(Model.Body)
    </p>

    <hr />

    <div class="well">
        <h4>Leave a Comment:</h4>
        @Html.Partial("PostComment", new SimpleBlog.Comment(), new ViewDataDictionary {{"PostId",Model.ID} })
    </div>
    <hr />

PostComment.cshtml

@model SimpleBlog.Comment

@using (Ajax.BeginForm("PostComment", "Home", new { PostId = Convert.ToInt32(ViewData["PostId"]) }, new AjaxOptions { HttpMethod = "POST" }))
{
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.TextAreaFor(model => model.Body, 3, 10, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Body, "", new { @class = "text-danger" })
    </div>

    <input type="submit" value="Submit" class="btn btn-primary" />
}

评论控制器:

[HttpPost]
        public ActionResult PostComment(Comment comment, int PostId)
        {
            if (comment != null)
            {
                comment.PostID = PostId;
                string sdate = DateTime.Now.ToShortDateString();
                comment.DateTime = DateTime.Parse(sdate);
                db.Comments.Add(comment);
                db.SaveChanges();
                return RedirectToAction("ReadMore");
            }
            return View();
        }

错误如下: 参数字典包含 'SimpleBlog.Controllers.HomeController' 中方法 'System.Web.Mvc.ActionResult ReadMore(Int32)' 的不可为空类型 'System.Int32' 的参数 'Id' 的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。 参数名称:parameters

请帮助我,非常感谢。

您要重定向到 (ReadMore) 的函数需要您传递 (int) 类型的 ID。

尝试以下操作:

[HttpPost]
        public ActionResult PostComment(Comment comment, int PostId)
        {
            if (comment != null)
            {
                comment.PostID = PostId;
                string sdate = DateTime.Now.ToShortDateString();
                comment.DateTime = DateTime.Parse(sdate);
                db.Comments.Add(comment);
                db.SaveChanges();
                return RedirectToAction("ReadMore",new { Id = PostId});
            }
            return View();
        }