将下拉列表选择的值及其文本框值绑定到模型 MVC5

Bind the dropdownlist selected value and its textbox value to Model MVC5

我有一个用于创建新登录信息的表单。在 post 期间,我必须将登录信息与安全问题和答案绑定在一起。我已将安全问题绑定到数据库中的下拉列表。如何将问题 ID 和文本值(用于回答)绑定到模型并将其传递给数据库 table?

这是我的代码

型号

[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 上有一个 foolproof [NotEqualTo] 或类似的验证属性,这样用户就不能 select 再次提出相同的问题

此处更改模型意味着您需要根据您的视图创建一个 Viewmodel 并将您的 属性 个模型分别映射到此 viewModel .