在Post上的模型中保留SelectList
在MVC4中:
我的模型中有以下属性用于下拉列表:
public SelectList Subjects { get; set; }
我在页面加载的Index()Action中设置了Subjects属性并返回模型。
使用SelectListItems可以很好地填充下拉列表。
@Html.DropDownListFor(x => x.Subject, new SelectList(Model.Subjects, "Text", "Text", "Other"))
当我提交表单时,模型中的Subjects SelectList已更改为null。 必须有一种简单的方法来持久化HttpPost。 我想我也想提交和发布这个SelectList,以及所有表单字段? 我该怎么办?
通常接受在Post
操作之后重新填充SelectList
。 只需在方法中提取它并在Get
和Post
操作中调用它。
将它再次发回控制器是不可能的。 您可以在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)MemoryCache.Default.Get("SubjectList"); } else { // The select list does not yet exists in the cache, fetch items from the data store. List 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命名空间 。
此外,缓存应位于控制器(或业务层)与数据访问层之间的单独层中,这只是为了清晰起见。
浏览器仅回发表单元素上的选定值。 此外,回发可以从数据存储中检索的值不是一个好主意。 您必须像填充列表时那样拉出列表中的项目。
此外,MVC不像.NET网页那样维护页面的状态,因为它没有视图状态。 开发人员完全负责管理回发之间的页面状态,这是MVC设计模式的本质。