c# - issue with using DbContext and returning view with the model -


i need fetch database , return model if modelstate not valid, seem not able use using , want to.

so code works:

[httppost]         public actionresult editproduct(productvm productvm, httppostedfilebase file)         {             // check model state             if (!modelstate.isvalid)             {                 db db = new db();                 productvm.categories = new selectlist(db.categories, "id", "name");                  return view(productvm);              }              return view(productvm);         } 

and code throws following error:

the operation cannot completed because dbcontext has been disposed.  [httppost] public actionresult editproduct(productvm productvm, httppostedfilebase file) {     // check model state     if (!modelstate.isvalid)     {         using (db db = new db())         {             //db db = new db();             productvm.categories = new selectlist(db.categories, "id", "name");         }          return view(productvm);      }      return view(productvm); } 

can somehow use using , still have work?

as @stephen muecke said must materialize collection using tolist() or asenumerable(). if don't enumarate collection, won't run immediately. that's why getting error. should be;

productvm.categories = new selectlist(db.categories.tolist(), "id", "name"); 

hope helps,


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -