加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:06:03 所属栏目:百科 来源:网络整理
导读:这是一个非常简单的例子,但它应该足以证明我的问题.我需要将模型传递给我的用户将更新的视图,但视图还需要一些其他数据来创建下拉列表或提供其他信息. 基于我下面的代码,我想避免使用ViewBag / ViewData,所以我是否以某种方式将QuestionList和PasswordLength
这是一个非常简单的例子,但它应该足以证明我的问题.我需要将模型传递给我的用户将更新的视图,但视图还需要一些其他数据来创建下拉列表或提供其他信息.

基于我下面的代码,我想避免使用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;
    };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读