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

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

基于我下面的代码,我想避免使用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;
    };
原文链接:/csharp/100705.html

猜你在找的C#相关文章