Most of my action methods return PartialViews on success and RedirectToAction results on failure. For that, I would like to copy the model state errors into TempData so I could display them to the user. I've read several questions here on SO and some external links but none of them worked for me... I'm decorating the ActionMethod with ModelStateToTempData
attribute from MvcContrib, then displaying it as follows in the view: (this is just a prototype)
@if (TempData.Count > 0)
{
foreach (var obj in TempData)
{
var errors = ((ModelStateDictionary)obj.Value).Values;
foreach (var error in errors)
{
<div style="position:absolute; background:Black; color:White; top:250px; left:550px;">
<span style="margin-bottom:5px; display:block; height:25px;">@error.Value</span>
</div>
}
}
}
Rather than displaying the error itself, I keep getting System.Web.Mvc.ValueProviderResult
. I know this is all wrong, and eventually I would want to filter the model state errors into a dictionary inside the TempData but for now I just want to have the error string displayed in the view.
P.S: I've tried to do it manually without the MvcContrib attribute, and I got the same result. But I do prefer to use my own code so I could have more control over the whole issue.
Any suggestions?
Ok After trying a million things, I found the answer myself... :)
And in the view:
UPDATE:
Here it is inside an ActionFilter:
You should seriously consider this concept: http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg
I started going down this road, and then read your answer. I combined them into the following files:
TempDataDictionaryExtensions.cs
I created extension methods to do the dirty work on the TempData, because I felt it didn't belong in the Action Filter itself.
TempDataModelStateAttribute.cs
My original, copied the errors out of
TempData
back intoModelState
prior to the ActionResult executing viaOnResultExecuting
. This is a combination of copying them intoTempData
and back out.