开发者

Best practice for returning a response from a partial view

I'm writing a simple blogging platform with ASP.NET MVC. My question is regarding forms contained in partial views and handling the response, validation errors or success, from the controller.

I have a blog post item view which has an associated controller that returns a post for a given URL. Embedded in this v开发者_JAVA技巧iew is a partial view containing a form for submitting comments on the post. The partial view form submits to a separate controller that handles adding comments. Inside the add comment action I perform validation and add errors to the ModelState object.

The problem is that I have to return a RedirectResult on the partial view action so that the user is returned to the originating post item, which means that I lose the ModelState object or any success messages I want to return.

I've seen people mention the use of TempData to pass validation or success information back to the original view, but to me this sounds a bit hackish. Is this really the solution? If so can anyone recommend a good example of its usage? If not, is this a sign of bigger problems in my chosen architecture?


I have used the PRG Pattern in the past give it a try

Use PRG Pattern for Data Modification


You can have the add comment action call the view post action...

Something like this I guess:

public class PostController
{
    ... blah ...

    public ActionResult ViewPost(int postId)
    {
        Post post = PostRepository.GetPost(postId);
        return View("ViewPost", post);
    }

    public ActionResult AddComment(int postId, string comment, string otherInfo)
    {
        //Validate stuff, setting modelstate etc

        //If it isn't valid, return the same post view (modelstate will stay)
        if (!ModelState.IsValid)
            return this.ViewPost(postId);

        //If it is valid then we want to save it and follow PRG pattern
        PostRepository.Save(newValidComment);
        TempData["Message"] = "Thanks for your comment!";
        return RedirectToAction("ViewPost", new {id = postId});
    }
}

Or a variation of the same concept...

HTHs,
Charles


Have you considered using the Ajax libraries to just post that area of the page? That way you wouldn't need to redirect.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜