Note that there are some explanatory texts on larger screens.

plurals
  1. POAre there any good reasons to not remove valid ModelState entries in OnActionExecuted?
    primarykey
    data
    text
    <p>Something I've found to be intensely annoying about ASP.NET MVC is that ModelState values are very persistent with the @Html.* extension methods during POST requests. I understand that ModelState is there to allow persisting invalid user-entered values, however, MVC's handling of ModelState continues even for properties whose user-entered values are valid. Sometimes, this is undesirable behavior.</p> <p>For example, if you have an ID in the URL, and you set an ID property in your view model to a different value (this is a good sign that the ID names need to be more specific, but bear with me), the value you set will make it during a GET request, but during a POST, the value in ModelState will be used, which will have come from the route.</p> <p>This also happens with posted values. If, for some reason, you need to change a value which came from the client, the new value in the model will be ignored; you must also (or instead) update ModelState.</p> <p>To resolve this inconsistency, I've taken to adding this action filter to my MVC projects as a global filter:</p> <pre><code>public class RemoveValidModelStateFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var modelState = filterContext.Controller.ViewData.ModelState; var keys = modelState.Keys.ToArray(); foreach (var key in keys) { var entry = modelState[key]; if (entry.Errors.Count == 0) modelState.Remove(key); } } } </code></pre> <p>It's been working well for me so far, but I'm curious if I'm unintentionally creating any problems or losing functionality. I only use this on new projects and projects which I have full control over, so it won't create hidden issues with values not being communicated.</p> <p>I can see other developers potentially becoming confused when working on my projects, but I don't know of any other side-effects.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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