Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset ModelState values?

Tags:

asp.net-mvc

I am checking a model for validity in an action. The repository throws various exceptions depending on how the checks I carry out go, so the action contains a try-catch statement.

[AcceptVerb(HttpVerbs.Post)]
public ActionResult MyAction1(Action1Model Model)
{
    if (ModelState.IsValid)
        try
        {
             new MyModelRepository().CarryOutSomeChecks(Model);
             return View("SuccessfulView")
        }
        catch (ValidationException)
        {
             Model.Result = Result.Fail;
             ModelState.... <= I would like to reset the ModelState here.
        }
    return View(Model)
}

The view model contains some sensitive information, so if the checks fail I would like to return to the view and remove the values which were input by the user.

To complicate things in my view I call actually has two partial views in it that show a form each, so like:

@model MyProject.MyOverallViewModel
@{
}

@{Html.RenderPartial("MyAction1Form", Model.Action1ModelInstance);}
@{Html.RenderPartial("MyAction2Form", Model.Action2ModelInstance);}

I have tried doing Model = new Model() in the catch, but, even though the model passed to the view is all null, the values entered to the form are persisted. I assume this is because of ModelState... Is there a way to reset that?

I would like to avoid doing a RedirectToAction so that I can persist the result of my check within my model when the view is displayed again.

Any ideas?

like image 527
yu_ominae Avatar asked Nov 02 '25 14:11

yu_ominae


1 Answers

ModelState.Clear(); should do the job.

like image 55
Darin Dimitrov Avatar answered Nov 04 '25 15:11

Darin Dimitrov