Search code examples
c#asp.net-mvcmodelstate

How to save model state while redirecting to another action in ASP .NET MVC?


I have a Home Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var m = new ModelClass
                    {
                        Prop1 = 1,
                        Prop2 = "property 2"
                    };

        return View(m);
    }

    public ActionResult SubAction()
    {
        ModelState.AddModelError("key", "error message value");
        return RedirectToAction("Index");
    }

}

Model:

public class ModelClass
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
}

and view:

@model MvcApplication9.Models.ModelClass
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.TextBoxFor(m => m.Prop1)
@Html.TextBoxFor(m => m.Prop2)

@Html.ValidationMessage("key")
<br/>
@Html.ActionLink("action", "SubAction", "Home")

when I click action actionlink I expect to see error message value but when I redirect from SubAction to Index action ModelState errors are lost. How can I save those model errors, set in SubAction, and display them in view, returned by Index action?


Solution

  • If you're just trying to get an error message across, use TempData:

    TempData.Add("error", "I'm all out of bubblegum...");
    

    Then, in your other action or it's view, you can use TryGetValue:

    object message = string.Empty;
    
    if(TempData.TryGetValue("error", out message)
    {
         // do something with the message...
    }