提交时,复选框列表中的选定选项未被粘贴到ActionResult

本文关键字:选项 ActionResult 复选框 列表 提交 | 更新日期: 2023-09-27 18:24:49

我在表单中有CheckBox列表和Radio列表,但在提交表单时,为任一列表选择的选项都不会传递给ActionResult。我错过了什么?

if (Model.IsMultipleChocie) { foreach (var Choice in Model.Choices) { <li> @Html.CheckBox("Answers", Choice.Value) @Html.Label(Choice.Key) </li> } } else { foreach (var Choice in Model.Choices) { <li> @Html.RadioButton("Answers", Choice.Value) @Html.Label(Choice.Key) </li> } }

public ActionResult ProcessVote(int[] Answers, int UserID, string UserIP, int ID)

提交时,复选框列表中的选定选项未被粘贴到ActionResult

@Html.CheckBox("Answers", Choice.Value)未设置value属性,因此需要使用@Html.CheckBox("Answers", new { value = Choice.Value })。但是,正如下面的注释中所指出的,@Html.Checkbox()使用value="false" so you posting back an array which includes int and bool值呈现第二个隐藏输入,因此绑定将失败。

手动创建复选框

<input type="checkbox" name="answerswer" value=@Choice.Value />

或者创建一个视图模型来表示要显示的内容。例如

public class AnswerVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}
public class MyVM
{
  public bool IsMultipleChoice { get; set; }
  public List<AnswerVM> Answers { get; set; }
  public int? SelectedAnswer { get; set ; } // for single choice
}

查看

@model MyVM
....
if (Model.IsMultipleChoice)
{
  for(int i = 0; i < Model.Answers.Count; i++)
  {
    @Html.HiddenFor(m => m.Answers[i].ID)
    @Html.CheckBoxFor(m => m.Answers[i].IsSelected)
    @Html.LabelFor(m => m.Answers[i].IsSelected, Model.Answers[i].Name) // associate label with the checkbox
  }
}
else
{
  foreach(var answer in Model.Answers)
  {
    @Html.RadioButtonFor(m => m.SelectedAnswer, @answer.ID)
    @Html.DisplayFor(m => m.Answers[i].Name)
  }
}

控制器

[HttpPost]
public ActionResult YourMethod(MyVM model)
{
  if(model.SelectedAnswer.HasValue)
  {
    // property SelectedAnswer contains the ID of the selected answer (from radio button)
  }
  else
  {
    foreach(AnswerVM answer in model.Answers)
    {
      if (answer.IsSelected)
      {
        // answer.ID contains the ID of the checked answers (from checkboxes)

注意:RadioButtonFor()呈现重复的id属性,因此您可以为每个属性提供一个唯一的ID(例如基于answer.ID),这样您就可以使用关联的<label for ..>