tags:

views:

115

answers:

1
    public ActionResult TestControl()
    {
        return PartialView();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult TestControl(FormCollection form)
    {
        if(!IsValid(form))
        {
            ModelState.AddModelError("_FORM", "Some error");
        }
        return Redirect(Request.UrlReferrer.AbsoluteUri);;
    }

If post have no errors all work fine. But how can I get the current model state in method TestControl() if I add some errors?

A: 

I had this same issue, and using the ValidationApplicationBlock and a small function I got this. All with help from referring to David Hayden's site (http://www.davidhayden.com/)

if (thread.HasErrors)
                {
                    AddValidationResults(thread.Errors, ViewData.ModelState, ValueProvider);
                    return View(thread);
                }

Then inside my BaseController I have:

protected static void AddValidationResults(ValidationResults results,
        ModelStateDictionary modelState, IDictionary<string,ValueProviderResult> valueProvider)
{
    foreach (ValidationResult result in results)
    {
        modelState.AddModelError(result.Key,result.Message);
        modelState.SetModelValue(result.Key, valueProvider[result.Key]);
    }
}

The key is the second line:

modelState.SetModelValue

Cheers,

Andrew

REA_ANDREW
No, I talk about another problemm. After ModelState.AddModelError("_FORM", "Some error");I have ModelState.Count == 1But in TestControl()I have ModelState.Count == 0, and I understand why but don't know how restore ModelState that was in TestControl(FormCollection form).
dotneter