3

I have an action method as below :

[HttpPost]
public ActionResult Edit(EditViewModel model)
{
    if (ModelState.IsValid)
    {
        //Do Something                
    }
    var model1 = new IndexViewModel();
    ModelState.AddModelError("", "An error occurred while editing the user.");
    return RedirectToAction("Index", model1);
}

On validation error, i want it to be transferred to the below method with the Model State error.

[HttpGet]
public ActionResult Index(IndexViewModel model)
{
    IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
}

My index.cshtml has a validation summary defined to display the model state error.

<div class="row">
    <div class="col-xs-12">
        @Html.ValidationSummary("", new { @class = "alert alert-danger validation" })
    </div>
</div>

Is there a way i can pass the model state error from the Edit method to the index method and load it on load of index screen? The current code is not working. The allErrors field is empty and does not contain any of the added errors.

TheFallenOne
  • 1,598
  • 2
  • 23
  • 57
  • Look at [TempData](https://stackoverflow.com/questions/12422930/using-tempdata-in-asp-net-mvc-best-practice). That's its purpose in life. – Kenneth K. Jul 24 '19 at 15:30

1 Answers1

2

As you can see, passing the ViewModel to RedirectToAction() would not persist the model errors. As mentioned by @Shyju in this post, the RedirectToAction() helper method causes a new GET request to be issued. You can use TempData to persist your object to the next action method, however. You can use the following code to achieve this:

[HttpPost]
public ActionResult Edit(EditViewModel model)
{
     TempData["EditViewModel"] = model;

     if (ModelState.IsValid)
     {
        //Do Something                
     }
     var model1 = new IndexViewModel();
     ModelState.AddModelError("", "An error occurred while editing the user.");
     return RedirectToAction("Index", model1);
}



 [HttpGet]
public ActionResult Index(IndexViewModel model)
{
  model = TempData["IndexViewModel"] as IndexViewModel;                

  IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
}

For more information, you can look at this Post.

Correia7
  • 364
  • 3
  • 10