2015-07-13 73 views
0

我正在创建简单的博客,在我的文章中我有'评论'部分功能。我可以将数据传递给控制器​​并成功保存数据,但返回包含“注释”的文章视图时会发生错误。如何返回到包含渲染部分的视图

这里是我的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”的空项。可选参数必须是引用类型,可为空类型,或者声明为可选参数。 参数名称:参数

请帮助我,非常感谢。

回答

0

您正在重定向到(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(); 
     } 
+1

非常感谢你。我做的。 – Jane2

+0

很高兴帮助:) – Ala