Note that there are some explanatory texts on larger screens.

plurals
  1. POPreserving an error message across multiple hops in ASP.NET MVC
    text
    copied!<p>Imagine you've got n pages, each of which approximately shares the same sort of model but that model has to be in a particular state before you can access certain pages.</p> <p>So if the user types in a URL to take them to page m, but this page is not accessible at the moment, the controller adds an error message to a collection of errors in TempData then redirects to page m-1.</p> <p>The problem is when page m-1 is also not accessible. If we add a message to the same collection (with the same key) in TempData, we don't see it on page m-2 as it gets removed from TempData before the request for page m-2 gets underway.</p> <p>I can imagine a solution where we have multiple error keys and each time we want to add an error or get errors back we try each key in turn, but has anyone got any better ideas? (I know that in theory I could work out the correct page to redirect to straight off but that is going to take a lot of rework and I don't have much time!)</p> <p><strong>EDIT:</strong></p> <p>This is the sort of thing I was thinking about:</p> <pre><code> protected void AddError(string error) { int keyCounter; var errors = GetErrors(out keyCounter); errors.Add(error); TempData.Remove(GetKey(keyCounter + 1)); TempData[GetKey(keyCounter + 1)] = errors; } protected List&lt;string&gt; GetErrors() { int jnk; return GetErrors(out jnk); } private string GetKey(int i) { return string.Format("ErrorKey:{0}", i); } private List&lt;string&gt; GetErrors(out int keyCounter) { keyCounter = 0; List&lt;string&gt; errors = null; for (int ii = 0; ii &lt; MaxErrorKeyCounter; ii++) { string tryKey = GetKey(ii); if (TempData.ContainsKey(tryKey)) { keyCounter = ii; errors = (List&lt;string&gt;)TempData[tryKey]; } } if (errors == null) errors = new List&lt;string&gt;(); return errors; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload