views:

186

answers:

3

In my blog engine, I have one controller action that displays blog content, and in that view, I call Html.RenderAction(...) to render the "CreateComment" form. When a user posts a comment, the post is handled by the comment controller (not the blog controller).

If the comment data is valid, I simply return a Redirect back to the blog page's URL.

If the comment data is invalid (e.g. comment body is empty), I want to return the ViewData with the error information back to the blog controller and through the blog view to the CreateComment action/view so I can display which fields are bad.

I have this working fine via AJAX when Javascript is enabled, but now I'm working on the case where Javascript might be disabled.

If I return a RedirecToAction or Redirect from the comment controller, the model state information is lost.

Any ideas?

A: 

If Javascript is enabled in the browser, why don't you set a bit of state information in the view when you perform the AJAX call? Then, when you post to the blog controller, the blog controller will know whether or not your comment was handled via AJAX, or whether the blog controller has to handle it itself.

Your blog controller method will have to accept a ViewModel object that contains the newly-created comment information.

Robert Harvey
A: 

You could store your ModelState or ViewData (which contains ModelState) in TempData before you do the redirect, and then fetch it afterwards:

// In your CreateComment action before redirect
if (!ModelState.IsValid)
{
    TempData["ViewData"] = ViewData;
}

// In your Blog controller's action to which you redirected
if (null != TempData["ViewData"])
{
    ViewData = (ViewDataDictionary)TempData["ViewData"];
}

Alternatively, you could create your own RouteData, set the "controller" and "action", clear the Response, grab this.Context and dump it into a new RequestContext, create a new IController using ControllerBuilder using the route data you created before, and then rewrite your path and execute the controller using the new request context. Somewhere in there you'd have to dump in your ModelState to carry over. I haven't tried it, and that seems overkill.

Chris F
A: 

Put the errors into TempData bevore redireting by using this filter from MVCContrib

http://www.jeremyskinner.co.uk/2008/10/18/storing-modelstate-in-tempdata-with-aspnet-mvc/

Malcolm Frexner