我注意到,在NerdDinner应用程序中,如果ModelState对于晚餐无效,它只返回模型的视图:
if (ModelState.IsValid) { ... return RedirectToAction("Details",new { id=dinner.DinnerID }); } return View(dinner);
然而,在我的应用程序中,模型(在这种情况下的视图模型)包含多个SelectLists.这些列表在这一点上没有被实例化,因为这个视图模型只是从表单提交中填充.在将此选择列表发回给用户之前,建议重新填充此选项的方法是什么?
这就是我想要我的控制器做的:
public ActionResult Save(MyModel model) { if (ModelState.IsValid) { businessClass.Save(model); return RedirectToAction("Index","Home"); } // This won't work because model has uninstantiated SelectLists return View("MyView",model); }
如果ModelState无效,我不想将模型发送到我的业务逻辑,但将控制器中的SelectList种群代码似乎没有任何意义.我应该在我的业务逻辑中创建一个公共方法,只是为了在我的视图模型上做这样的事情吗?
解决方法
我个人喜欢保持简单:
[HttpGet] public Edit(int id) { EditForm form = new EditForm(); // Populate from the db or whatever... PopulateEditPageSelectLists(form); return View(form); } [HttpPost] public Edit(EditForm form) { if (ModelState.IsValid) { // Do stuff and redirect... } PopulateEditPageSelectLists(form); return View(form); } public void PopulateEditPageSelectLists(form) { // Get lookup data from the db or whatever. }
如果填充选择列表的逻辑是各种各样的疯狂,可能值得移动到单独的类或任何它,但作为第一步这是最好的开始的地方.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。