I have the following two action methods (simplified for question):
[HttpGet]
public ActionResult Create(string uniqueUri)
{
// get some stuff based on uniqueuri, set in ViewData.
return View();
}
[HttpPost]
public ActionResult Create(Review review)
{
// validate review
if (validatedOk)
{
return RedirectToAction("Details", new { postId = review.PostId});
}
else
{
ModelState.AddModelError("ReviewErrors", "some error occured");
return RedirectToAction("Create", new { uniqueUri = Request.RequestContext.RouteData.Values["uniqueUri"]});
}
}
So, if the validation passes, i redirect to another page (confirmation).
If an error occurs, i need to display the same page with the error.
If i do return View()
, the error is displayed, but if i do return RedirectToAction
(as above), it loses the Model errors.
I'm not surprised by the issue, just wondering how you guys handle this?
I could of course just return the same View instead of the redirect, but i have logic in the "Create" method which populates the view data, which i'd have to duplicate.
Any suggestions?
Microsoft removed the ability to store complex data types in TempData, therefore the previous answers no longer work; you can only store simple types like strings. I have altered the answer by @asgeo1 to work as expected.
From here, you can simply add the required data annotation on a controller method as needed.
I suggest you return the view, and avoid duplication via an attribute on the action. Here is an example of populating to view data. You could do something similar with your create method logic.
Here is an example:
I prefer to add a method to my ViewModel which populates the default values:
Then I call it when ever I need the original data like this: