[英]Bind the dropdownlist selected value and its textbox value to Model MVC5
我有一個表單來創建新的登錄信息。 在發布期間,我必須將登錄信息以及安全性問題和答案綁定在一起。 我已將安全性問題綁定到數據庫的下拉列表中。 如何將問題ID和文本值(用於答案)綁定到模型,並將其傳遞給DB表?
這是我的代碼
模型
[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" })
將您的模型更改為(屬性省略)
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
旁注:您可能希望在Question2
上具有萬無一失的 [NotEqualTo]
或類似驗證屬性,以便用戶無法再次選擇同一問題
在這里更改模型意味着您需要根據您的視圖創建一個Viewmodel並將模型的屬性分別映射到該viewModel。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.