我有一个表单来创建新的登录信息。在帖子中,我必须绑定登录信息以及安全问题和答案。我已将安全问题绑定到DB的下拉列表中。如何将问题ID和文本值(用于答案)绑定到模型并将其传递给数据库表?
这是我的代码
模型
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Display(Name = "Question1")]
public List<string> Question1 { get; set; }
[Required]
[Display(Name = "Question2")]
public string Question2 { get; set; }
[Required]
[Display(Name = "Answer1")]
public List<string> Answer1 { get; set; }
[Required]
[Display(Name = "Answer2")]
public string Answer2 { get; set; }
public SelectList QuestionList { get; set; }
控制器
[HttpGet]
public ActionResult NewLogin()
{
myDB dbCon = new myDB();
ViewBag.QuestionList = new SelectList(dbCon.GetQuestion(), "ID", "Value");
return View();
}
[HttpPost]
public ActionResult NewLogin()
{
if (ModelState.IsValid)
{
p.Email = model.Email;
p.pass = model.password;
// how to get the Question ID and Answer here ?
//each user has its own ID where this ID is related to two questions ID in the database
}
return View(model);
}
查看
@Html.DropDownListFor(m=>m.ID,new SelectList(Model.QuestionList,"ID","Value"),"Select a question")
@Html.TextBoxFor(m => m.Answer1, new { @class = "form-control" })
@Html.DropDownListFor(m=>m.ID,new SelectList(Model.QuestionList,"ID","Value"),"Select a question")
@Html.TextBoxFor(m => m.Answer2, new { @class = "form-control" })
答案 0 :(得分:0)
将模型更改为(省略属性)
Tenancy
TenancyUser
TenancyUserAccount
TenancyUserAccountAccountItem
在控制器中
public class LoginModel
{
public string Email { get; set; }
public string Password { get; set; }
public int Question1 { get; set; } // change
public int Question2 { get; set; } // change
public string Answer1 { get; set; } // change
public string Answer2 { get; set; }
public SelectList QuestionList { get; set; }
}
在视图中
myDB dbCon = new myDB();
[HttpGet]
public ActionResult NewLogin()
{
// Initialize the model and assign the SelectList
LoginModel model = new LoginModel()
{
QuestionList = SelectList(dbCon.GetQuestion(), "ID", "Value")
};
return View(model);
}
[HttpPost]
public ActionResult NewLogin(LoginModel model)
{
// Save the user and get their ID
// Save the values of UserID, Question1, Answer1
// and UserID, Question2, Answer2 to your Answers table
}
附注:您可能希望@model LoginModel
....
@Html.DropDownListFor(m => m.Question1, Model.QuestionList, "Select a question")
@Html.TextBoxFor(m => m.Answer1)
// ditto for Question2 and Answer2
上有foolproof [NotEqualTo]
或类似的验证属性,因此用户无法再次选择相同的问题
答案 1 :(得分:0)
此处更改模型意味着您需要根据视图创建一个Viewmodel,并将模型的属性分别映射到此viewModel