这是一个非常简单的例子,但它应该足以证明我的问题.我需要将模型传递给我的用户将更新的视图,但视图还需要一些其他数据来创建下拉列表或提供其他信息.
基于我下面的代码,我想避免使用ViewBag / ViewData,所以我是否以某种方式将QuestionList和PasswordLength(为多余的示例场景引入)组合到ChangeSecurityQuestionModel中或者创建一个新的viewmodel或其他一些对象?
[Authorize] public ActionResult ChangeSecurityQuestion() { var user = Membership.GetUser(); if (user != null) { var model = new ChangeSecurityQuestionModel() { PasswordQuestion = user.PasswordQuestion }; ViewBag.QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(),"Question","Question"); ViewBag.PasswordLength = MembershipService.MinPasswordLength; return View(model); } // user not found return RedirectToAction("Index"); } [Authorize] [HttpPost] public ActionResult ChangeSecurityQuestion(ChangeSecurityQuestionModel model) { if (ModelState.IsValid) { var user = Membership.GetUser(); if (user != null) { if (user.ChangePasswordQuestionAndAnswer(model.Password,model.PasswordQuestion,model.PasswordAnswer)) { return View("ChangeQuestionSuccess"); } else { ModelState.AddModelError("","The password is incorrect."); } } } // If we got this far,something Failed,redisplay form ViewBag.QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(),"Question"); ViewBag.PasswordLength = MembershipService.MinPasswordLength; return View(model); }
解决方法
为什么不将QuestionList和PasswordLength放在ChangeSecurityQuestionModel中
var model = new ChangeSecurityQuestionModel() { PasswordQuestion = user.PasswordQuestion,QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(),"Question"),PasswordLength = MembershipService.MinPasswordLength; };