I have the following table:
CREATE TABLE CATEGORIES
(
ID NUMBER(1,0) PRIMARY KEY,
CATEGORY VARCHAR2(20)
);
INSERT INTO CATEGORIES VALUES(1,"General");
INSERT INTO CATEGORIES VALUES(2,"Interior");
INSERT INTO CATEGORIES VALUES(3,"Exterior");
INSERT INTO CATEGORIES VALUES(4,"Tuning");
INSERT INTO CATEGORIES VALUES(5,"Body");
And I have an enum that exactly matches the above table:(Please don't ask why)
public enum Category
{General=1,Interior,Exterior,Tuning,Body}
Here's my view model:
public class OrdersViewModel{
public IEnumerable<SelecListItem> Categories{get;set;}
public Order Order{get;set;}
}
public Order{
public Category Category{get;set;}
}
I use memory cache to avoid traveling to the database, so I've got the following method that gets object from cache if it exists, otherwise fetches from the database:
public T GetItemFromCache<T>(string key, Func<T> getFromDb) where T : class
{
T item = MemoryCache.Default.Get(key) as T;
if (item == null)
{
item = getFromDb();
if (item != null)
MemoryCache.Default.Add(key, item, DateTime.Now.AddMinutes(1));
}
return item;
}
In my action method I do the following:
public ActionResult Index(){
MyViewModel vm=new MyViewModel();
vm.Categories =
GetItemFromCache("categories", () =>
context.Categories.OrderBy(x => x.ID).ToList().Select(x => new
SelectListItem { Value = x.ID.ToString(), Text = x.Category }));
}
And finally in view I do this:
@Html.DropDownListFor(x => x.Order.Category, Model.Categories, "",)
In the action method, as you can see, I use entity framework for fetching records from database and I order items by ID. So they always have to be ordered. The problem is, periodically, the position of the last two items in the result list are swapped, so instead of being:
General,Interior,Exterior,Tuning,Body
I get
General,Interior,Exterior,Body,Tuning
And I fix this by just restarting the IIS. Recycling the pool also does the job. I don't use any javascript for populating the dropdownlist. Do you have any idea what the problem might be?