c# – 如何避免ViewBag(或ViewData)支持模型?

前端之家收集整理的这篇文章主要介绍了c# – 如何避免ViewBag(或ViewData)支持模型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个非常简单的例子,但它应该足以证明我的问题.我需要将模型传递给我的用户将更新的视图,但视图还需要一些其他数据来创建下拉列表或提供其他信息.

基于我下面的代码,我想避免使用ViewBag / ViewData,所以我是否以某种方式将QuestionList和PasswordLength(为多余的示例场景引入)组合到ChangeSecurityQuestionModel中或者创建一个新的viewmodel或其他一些对象?

  1. [Authorize]
  2. public ActionResult ChangeSecurityQuestion() {
  3. var user = Membership.GetUser();
  4. if (user != null) {
  5. var model = new ChangeSecurityQuestionModel() {
  6. PasswordQuestion = user.PasswordQuestion
  7. };
  8. ViewBag.QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(),"Question","Question");
  9. ViewBag.PasswordLength = MembershipService.MinPasswordLength;
  10. return View(model);
  11. }
  12.  
  13. // user not found
  14. return RedirectToAction("Index");
  15. }
  16.  
  17. [Authorize]
  18. [HttpPost]
  19. public ActionResult ChangeSecurityQuestion(ChangeSecurityQuestionModel model) {
  20. if (ModelState.IsValid) {
  21. var user = Membership.GetUser();
  22. if (user != null) {
  23. if (user.ChangePasswordQuestionAndAnswer(model.Password,model.PasswordQuestion,model.PasswordAnswer)) {
  24. return View("ChangeQuestionSuccess");
  25. } else {
  26. ModelState.AddModelError("","The password is incorrect.");
  27. }
  28. }
  29. }
  30.  
  31. // If we got this far,something Failed,redisplay form
  32. ViewBag.QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(),"Question");
  33. ViewBag.PasswordLength = MembershipService.MinPasswordLength;
  34. return View(model);
  35. }

解决方法

为什么不将QuestionList和PasswordLength放在ChangeSecurityQuestionModel中
  1. var model = new ChangeSecurityQuestionModel() {
  2. PasswordQuestion = user.PasswordQuestion,QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(),"Question"),PasswordLength = MembershipService.MinPasswordLength;
  3. };

猜你在找的C#相关文章