通常认为您SelectList
在操作后重新填充 a Post
。只需在方法中提取它并在Get
andPost
操作中调用它。
将其再次发布回控制器不是要走的路。您可以缓存 SelectList 中的项目,这样您就不必对数据存储进行两次查询。
例子:
public ActionResult Create()
{
var model = new SubjectModel();
PopulateSubjectList(model);
return View(model);
}
[HttpPost]
public ActionResult Create(SubjectModel model)
{
if (ModelState.IsValid)
{
// Save item..
}
// Something went wrong.
PopulateSubjectList(model);
return View(model);
}
private void PopulateSubjectList(SubjectModel model)
{
if (MemoryCache.Default.Contains("SubjectList"))
{
// The SubjectList already exists in the cache,
model.Subjects = (List<Subject>)MemoryCache.Default.Get("SubjectList");
}
else
{
// The select list does not yet exists in the cache, fetch items from the data store.
List<Subject> selectList = _db.Subjects.ToList();
// Cache the list in memory for 15 minutes.
MemoryCache.Default.Add("SubjectList", selectList, DateTime.Now.AddMinutes(15));
model.Subjects = selectList;
}
}
注意:MemoryCache
使用System.Runtime.Caching
命名空间。请参阅:System.Runtime.Caching 命名空间。
此外,缓存应该位于控制器(或业务层)和数据访问层之间的单独层中,这只是为了清楚起见。