2015-07-13 79 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