0

If we are using ajax call to return partial view, then response from the action method may return cached output from partial view. The issue has been discussed on several SO post here, here, here

To resolve issue i have to do ModelState.Clear() in action method.

I have several action methods that returns partial view using Ajax call. So i thought instead of doing ModelState.Clear() in each method i can create custom ActionFilterAttribute like below

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {            
        filterContext.Controller.ViewData.ModelState.Clear();
        base.OnResultExecuting(filterContext);
    }
 }

and then register it with global filters

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {                    
        filters.Add(new NoCacheAttribute());
    }

This seems to be working fine.

However I wanted to know if there is there any undesirable effect doing ModelState.Clear() before action executing? If not, then why that is not a default behavior in asp.net mvc

LP13
  • 30,567
  • 53
  • 217
  • 400
  • using `ModelState.Clear()` has nothing to do with cached output –  Oct 19 '17 at 20:59
  • It does. Please see the links provided. Also `NoCacheAttribute` is just a name of the class. May be the name of the class is confusing – LP13 Oct 19 '17 at 21:30
  • No it does not! And your first link does not work. The 2nd link is because the parameter is the same as the model property so its added to `ModelState`. And ditto for the 3rd (the accepted answer claims its a bug but its not. And to explain why, refer the 2nd part of [this answer](https://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) –  Oct 19 '17 at 21:34
  • You have not shown your method and its parameters or the model but I assume you have the same issue as per the 2nd link. Which is easily solved by using a different name for the parameter. Again - its not being cached - its constructing a new model –  Oct 19 '17 at 21:36
  • And are there side effects - yes, none of your POST methods will ever be able to test `ModelState.IsValid` –  Oct 19 '17 at 21:38

0 Answers0