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

标签 c# asp.net-mvc asp.net-mvc-3

这是一个非常简单的例子,但足以说明我的问题。我需要向我的 View 传递一个用户将更新的模型,但该 View 还需要一些其他数据来创建下拉列表或提供其他信息。

根据我下面的代码,我想避免使用 ViewBag/ViewData,所以我以某种方式组合 QuestionListPasswordLength(在多余的示例场景中加入)到 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", "Question");
  ViewBag.PasswordLength = MembershipService.MinPasswordLength;
  return View(model);
}

最佳答案

为什么不将 QuestionList 和 PasswordLength 放入您的 ChangeSecurityQuestionModel

var model = new ChangeSecurityQuestionModel() {
      PasswordQuestion = user.PasswordQuestion,
      QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(), "Question", "Question"),
      PasswordLength = MembershipService.MinPasswordLength;
    };

关于c# - 如何避免 ViewBag(或 ViewData)以支持模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5193078/

相关文章:

asp.net-mvc-3 - 数据库资源管理器不显示数据库和表

asp.net-mvc-3 - 何时应该在 Ninject.MVC3 中使用 Kernel.BeginBlock()

c# - 如何使用 C# 更好地查询 Active Directory 中的多个域?

asp.net-mvc - 将请求重定向到另一个 url

在下拉列表中选择项目时,jQuery 在 IE 中不起作用

jquery - ASP.net MVC 3 导航 Accordion 图像路径

asp.net-mvc - 用于 json 嵌套数组的 MVC3 绑定(bind)

c# - 如何使用servicestack批量sql调用

c# - 包含子元素集合的配置元素

c# - CSS 中的 LinkedResource