I have a controller in an ASP.NET MVC application. The page has several filters on it, that are represented in the controller by a Dictionary object. The filter dictionary looks like the following:
Dictionary<string,bool> filterMap = new Dictionary<string,bool>();
filterMap.Add("Accepted",true);
filterMap.Add("Rejected",true);
filterMap.Add("Valid",true);
filterMap.Add("Invalid",true);
On the page, there are toggle buttons to set the values of there respect dictionary item(i.e. If the "Accepted" Button is toggled off, it changes the value on the dictionary item to false.
My problem I am experiencing is, every time the page is called, the dictionary resets in the constructors and is initialized to the above value.
I have the following in my constructor, but it doesn't help because the dictionary is reset and is null every time.
开发者_开发知识库public MyController(){
if (FilterMap == null)
{
FilterMap = new Dictionary<string, bool> {{"Accepted", true}, {"Returned",true}, {"Valid", true},{"Invalid",true}};
}
}
The easiest option would be to save the FilterMap
in Session:
private Dictionary<string, bool> FilterMap
{
get { return (Dictionary<string,bool>)Session["FilterMap"] ?? GetDefaultFilterMap(); }
set { Session["FilterMap"] = value; }
}
private static Dictionary<string, bool> GetDefaultFilterMap()
{
return new Dictionary<string, bool> {{"Accepted", true}, {"Returned",true}, {"Valid", true},{"Invalid",true}};
}
Then in your action to toggle the filters make sure you set FilterMap
again to save the change in Session
(not necessary if you use in-memory session state):
public ActionResult ShowReturned(bool show)
{
var filterMap = FilterMap;
filterMap["Returned"] = show;
FilterMap = filterMap;
}
Note that if your dictionary is only going to have these keys, you might as well use a real class with Accepted
, Returned
, etc. as properties.
精彩评论