多个操作,相同视图和验证错误

时间:2011-02-03 06:45:08

标签: asp.net views asp.net-mvc-3 models

让我们假设在一个名为AddComment()的动作中发生了ModelState错误。 AddComment没有自己的视图,因此我们必须返回View(“Blog”)而不是返回View()。我们不能使用RedirectToAction(“Blog”),因为我们失去了ModelState错误。如果博客视图绑定到博客模型,问题是什么?!?假设我们有一个Index()动作,它的工作是检索Blog的数据并返回View(“Blog”,BlogModel)。我们必须将检索BlogModel的Index()的内容复制到AddComment()操作中。否则,从AddComment返回View(“Blog”)将在解析Blog视图时给出一个null异常。这是在使用相同视图的操作之间维护ModelState错误的唯一方法吗?我刚刚开始学习MVC,我仍在学习正确的方法来布局我的代码所以请赐教。

    [HttpGet]
    public ActionResult Index()
    {
        BlogEntry RecentBlogEntry;

        //get the most recent blog entry
        RecentBlogEntry = m_BlogEntryDataService.GetRecentBlogEntry();

        return View(RecentBlogEntry);
    }

    [HttpPost]
    public ActionResult AddComment(BlogComment NewComment)
    {
        if (ModelState.IsValid)
            m_CommentDataService.AddComment(NewComment);

        //get the most recent blog entry - AGAIN
        return View("Index", m_BlogEntryDataService.GetRecentBlogEntry());
    }

1 个答案:

答案 0 :(得分:0)

您的代码是正确的。如果出现验证错误,您应该再次获取最新的博客条目,以便正确地重新显示视图。

相关问题