Search code examples
asp.net-mvc-3c#-4.0restful-architecture

MVC Rest and returning views


I'm trying to implement the restful convention on my controllers but am not sure how to handle failing model validation in sending it back to the 'New' view from the Create action.

public class MyController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult New()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(MyModel model)
    {
        if(!ModelState.IsValid)
        {
             // Want to return view "new" but with existing model
        }

        // Process my model
        return RedirectToAction("Index");
    }
}

Solution

  • Simply:

    [HttpPost]
    public ActionResult Create(MyModel model)
    {
        if(!ModelState.IsValid)
        {
            return View("New", model);
        }
    
        // Process my model
        return RedirectToAction("Index");
    }