gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:01:57 25 4
gpt4 key购买 nike

这是一个非常简单的例子,但足以说明我的问题。我需要向我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com