在单个视图中分组单选按钮,并正确发回表单数据

本文关键字:数据 表单 视图 单个 单选按钮 | 更新日期: 2023-09-27 18:10:14

我目前正在开发一个MVC应用程序,该应用程序涉及单个视图中的多组单选按钮。

当视图被发回时,我希望表单数据能够被自动解析和输入,以便控制器中的post back方法传递为每组单选按钮选择的选项。

下面是一些示例代码来说明这一点:

public class SurveyViewModel {
    public List<SurveyQuestion> Questions { get; set; }
}
public class SurveyQuestion
{
    public string Question { get; set; }
    public IEnumerable<SelectListItem> Options { get; set; }
    public int Answer { get; set; }
}
public class Option
{
    public int Value { get; set; }
    public string Text { get; set; }
}
控制器

    public ActionResult Survey()
    {
        List<string> questions = new List<string> { "Question 1", "Question 2", "Question 3" };

        SurveyViewModel model = new SurveyViewModel {
            Questions = new List<SurveyQuestion>()
        };

        foreach (string question in questions)
        {
            List<Option> list = new List<Option>();
            list.Add(new Option() { Value = 1, Text = "Answer 1" });
            list.Add(new Option() { Value = 2, Text = "Answer 2" });
            list.Add(new Option() { Value = 3, Text = "Answer 3" });
            SelectList sl = new SelectList(list, "Value", "Text");

            model.Questions.Add(new SurveyQuestion {
                Question = question,
                Answer = 1, // TODO: Get this from DB
                Options = sl
            });
        }
        return View(model);
    }
<<p> 视图/strong>
    @foreach (SurveyQuestion question in Model.Questions)
    {
        <p>@question.Question</p>
        @Html.RadioButtonForSelectList(m => question.Answer, question.Options)
    }
辅助

http://jonlanceley.blogspot.co.uk/2011/06/mvc3-radiobuttonlist-helper.html

如果我们只是坚持使用标准MVC(没有扩展),Html.RadioButtonFor助手最终输出单选按钮组,重复客户端的命名约定Option[0], Option[1], Option[2]等。

这将导致每个组的第一个选项被分组,每个组的第二个选项被分组,以此类推。

另一种方法是在Controller的post back Action中检查当前的请求表单数据,并手动解析它,但我希望利用MVC自动将传入数据转换为类型参数的能力,而不是自己做这件事。

谢谢你的帮助

在单个视图中分组单选按钮,并正确发回表单数据

不要为集合使用foreach循环,因为模型绑定器不能编写正确的标记,以便它正确绑定集合的每个项目。您需要使用for-loop:

for (var i = 0; i < Model.Questions.Count(); i++)
{
    <p>@Model.Questions[i].Question</p>
    @Html.RadioButtonForSelectList(m => Model.Questions[i].Answer, Model.Questions[i].Options)
}

您可以检查使用forloop编写的标记。现在每个问题都被索引了(例如Questions[0].Answer, Questions[1].Answer等等),这样模型绑定器就可以正确地完成它的工作了。我敢打赌,radiobuttonlist helper甚至不能与您当前的代码一起工作,因为它会以相同的名称(例如question.Answer)写出选项。因此,所有选项被视为一个组。