I have an MVC3 C#.Net web app. that has an import from Excel function. This function is performed in the Import method of the Rate controller. It is viewed in the Rate/Import view. When importing, some rows are successful, some are not. I am gathering the errors into a string[] array. The import is considered successful if one or more rows is successfully imported, therefore the app navigates back to the Proposal Edit view. I want to pass the informational errors back to the Proposal Edit view for display. Any ides how to do this?
-
By "the app navigates back to the Proposal Edit" do you mean you're doing a redirect after the form is submitted? If so, the only place you're going to be able to store information is in a database (passing an ID over to the other controller to go lookup the strings), in a session or in a cookie. The ViewBag/ViewData lifecycle ends with the life of the request. A redirect creates a new "Request" from the browser.Nick Bork– Nick Bork2012-02-09 16:48:17 +00:00Commented Feb 9, 2012 at 16:48
Add a comment
|
1 Answer
There are several ways.
TempData
This is available in your controller. TempData persists across a single redirect.
public ActionResult Process()
{
// ... Process your rows, get array of errors back ...
TempData["errors"] = errors;
return RedirectToAction("Edit");
}
public ActionResult Edit()
{
var errors = (IEnumerable<string>)TempData["errors"]; // Get the errors back.
return View(errors); // Pass into the view
}
ModelState
You could add these errors directly to the ModelState and then redisplay the edit form. It doesn't persist across a redirect.
public ActionResult Process()
{
// ... Process your rows, get array of errors back ...
for(var i = 0; i < errors.Length; i++)
{
ModelState.AddModelError("row" + i, errors[i]);
}
// Can't redirect here - ModelState doesn't persist.
return View("Edit");
}
Then, in your edit view, just display the validation summary:
@Html.ValidationSummary("The following row errors occured:");
This will render this html. The class is the default one set by MVC.
<div class="validation-summary-errors">
<span>The following row errors occured:</span>
<ul>
<li>...Error 1...</li>
... Other errors ...
</ul>
</div>
2 Comments
MikeTWebb
@leniency....thanks a lot. Good stuff! Question on the ModelState....how does the ModelState display the errors? Does there need to be more code in the Edit view? Thanks
Leniency
@MikeTWebb Yes, the last line,
@Html.ValidationSummary("The following row errors occured:"); is what displays any errors in the ModelState. Updated my answer with what that renders out.