开发者

Multiple Actions, Same View and Validation Errors

Let's assume ModelState errors occurred in an action called AddComment(). AddComment does not have it's own view, so instead of returning View(), we must return View("Blog"). We can't use RedirectToAction("Blog") because we loose our ModelState errors. The problem is what if the Blog view is bound to a Blog model?!? Let's assume we have an Index() action whose job it is to retrieve the Blog's data and returns View("Blog",BlogModel). We would have to copy the contents of Index(), where the BlogModel is retri开发者_运维技巧eved, to our AddComment() action. Else, returning View("Blog") from AddComment will give us a null exception when the Blog view is being parsed. Is this the only way to maintain ModelState errors between actions that use the same view? I just started learning MVC and I'm still learning the right way to layout my code so please enlighten me.

    [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());
    }


Your code is correct. You should get the most recent blog entry again if there was a validation error so that you can correctly redisplay the view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜