C# 重定向错误

C# 重定向错误,c#,asp.net-mvc,C#,Asp.net Mvc,在ASP.NET MVC的第一步中,我尝试创建一个简单而典型的带有评论的文章页面:在文章本身下面应该有一个表单,允许用户向文章发表评论 我使用以下方法为submit表单和CommentController创建了部分视图: public ActionResult Add(int entryId); [HttpPost] public ActionResult Add(Comment comment); 然后,在文章的HomeController视图下: 或者我甚至应该采取不同的方法?在另一个添

在ASP.NET MVC的第一步中,我尝试创建一个简单而典型的带有评论的文章页面:在文章本身下面应该有一个表单,允许用户向文章发表评论

我使用以下方法为submit表单和CommentController创建了部分视图:

public ActionResult Add(int entryId);

[HttpPost]
public ActionResult Add(Comment comment);
然后,在文章的HomeController视图下:

或者我甚至应该采取不同的方法?

在另一个添加操作上添加HttpGet

您应该/可能使用RenderPartial而不是RenderAction:


如果您所做的只是实例化一个您已经拥有ID的模型,那么似乎不需要使用操作方法。

这个答案可能有一个解释。我看到我在某个时候对它投了更高的票,所以它至少帮助了我:从数据库中获取评论的操作方法在哪里?没有。传递给view action Show的模型类有一组注释作为导航属性,因此显示它们不是问题。@Doe,您能为主控制器的Show操作添加代码吗?另外,您可以发布错误的堆栈跟踪吗?它可能会告诉我们错误发生在哪个控制器中。@Doe您不能使用return-RedirectToActionShow,Home,new{id=entry.EntryId};因为你正处于儿童行动中,这就是问题所在。这种逻辑不应该在子操作中,而应该在父操作中。它并没有真正改变任何事情。谢谢你的回答。
<div class="add-comment">
    @{ Html.RenderAction("Add", "Comment", new { entryId = Model.EntryId }); }
</div>
public ActionResult Add(int entryId)
{
    var comment = new Comment { EntryId = entryId };
    return PartialView(comment);
}

[HttpPost]
public ActionResult Add(Comment comment)
{
    if (ModelState.IsValid)
    {
        comment.Date = DateTime.Now;
        var entry = db.Entries.FirstOrDefault(e => e.EntryId == comment.EntryId);
        if (entry != null)
        {
            entry.Comments.Add(comment);
            db.SaveChanges();
            return RedirectToAction("Show", "Home", new { id = entry.EntryId });
        }
    }

    return PartialView(comment);
}
Html.RenderPartial("YourPartialView", new Comment { EntryId = Model.EntryId });