c# - ASP.NET MVC 5 组单选按钮

标签 c# asp.net asp.net-mvc

我正在开始我的第一个 ASP.NET MVC 项目,所以我有一个简单的问题。 我有以下代码:

foreach(var question in Model.GeneralQuestions)
{
    <div class = "well">
        <h3>
            <strong>@question.QuestionString</strong>
        </h3>
        @foreach (var answer in question.PossibleAnswers)
        {
            @Html.RadioButtonFor(model => question.QuestionString, answer.Answer)
            @Html.Label(answer.Answer)
            <br />
        }
    </div>
}

Model.GeneralQuestions 中的所有问题都是唯一的,因此单选按钮应按名称属性分组(每个问题一组单选按钮)。但是这段代码只产生一组,所以当我回答第二个问题时,第一个被取消选择。 我需要改变什么?

编辑
我的模型看起来像:

public class StudentViewModel
{
    public Student Student { get; set; }
    public List<Question> GeneralQuestions { get; set; }
    public List<SubjectQuestions> SubjectQuestions { get; set; }
}
public class Student
{
    public int StudentID { get; set; }
    public string Index { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }

    public virtual ICollection<Subject> Subjects { get; set; }
}
public class Question
{
    public int QuestionID { get; set; }
    public string QuestionString { get; set; }
    public bool IsAssociatedWithSubject { get; set; }

    public virtual ICollection<PossibleAnswer> PossibleAnswers { get; set; }
    public virtual ICollection<Results> Results { get; set; }
}
public class SubjectQuestions
{
    public Subject Subject { get; set; }
    public List<Question> Questions { get; set; }
}
public class Results
{
    public int ResultsID { get; set; }
    public int QuestionID { get; set; }
    public int? SubjectID { get; set; }
    public int PossibleAnswerID { get; set; }

    public virtual Question Question { get; set; }
    public virtual PossibleAnswer PossibleAnswer { get; set; }
    public virtual Subject Subject { get; set; }
}

在 StudentViewModel 的一个实例中,我保存了一名学生和他应该回答的所有问题(包括一般问题和与他正在学习的科目相关的问题)并将其传递给 View 。在 View 中,我将所有问题都放在单一形式中,它们都是 radio 类型。那么,任何人都可以帮助我对单选按钮进行分组并正确发回此表单吗?

最佳答案

您的代码存在许多问题,包括生成重复的 id(无效的 html),生成重复的 name 属性(这就是为什么您只创建一组,但更重要的是,这将阻止您在回发时绑定(bind)到模型)并且您实际上并没有绑定(bind)到有效的属性。

您将需要创建 View 模型来表示您想要显示和编辑的内容,并在 for 循环(或使用 EditorTemplate)中生成单选按钮,以便它们使用索引器正确命名。

查看模型

public class QuestionVM
{
  public int ID { get; set; } // for binding
  public string Text { get; set; }
  [Required]
  public int? SelectedAnswer { get; set; } // for binding
  public IEnumerable<AnswerVM> PossibleAnswers { get; set; }
}

public class SubjectVM
{
  public int? ID { get; set; }
  [DisplayFormat(NullDisplayText = "General")]
  public string Name { get; set; }
  public List<QuestionVM> Questions { get; set; }
}

public class AnswerVM
{
  public int ID { get; set; }
  public string Text { get; set; }
}

public class StudentVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  // plus any other properties of student that you want to display in the view
  public List<SubjectVM> Subjects { get; set; }
}

查看

@model YourAssembly.StudentVM
@using(Html.BeginForm())
{
  @Html.HiddenFor(m => m.ID)
  @Html.DisplayFor(m => m.Name)
  for(int i = 0; i < Model.Subjects.Count; i++)
  {
    @Html.HiddenFor(m => m.Subjects[i].ID)
    @Html.DisplayFor(m => m.Subjects[i].Name) // will display "General" if no name
    for (int j = 0; j < Model.Subjects[i].Questions.Count; j++)
    {
      @Html.HiddenFor(m => m.Subjects[i].Questions[j].ID)
      @Html.DisplayFor(m => m.Subjects[i].Questions[j].Text)
      foreach(var answer in Model.Subjects[i].Questions[j].PossibleAnswers )
      {
        <div>
          @Html.RadioButtonFor(m => m.Subjects[i].Questions[j].SelectedAnswer, answer.ID, new { id = answer.ID})
          <label for="@answer.ID">@answer.Text</label>
        </div>
      }
      @Html.ValidationMessageFor(m => m.Subjects[i].Questions[j].SelectedAnswer)
    }
  }
  <input type="submit" value="save" />
}

Controller

public ActionResult Edit(int ID)
{
  StudentVM model = new StudentVM();
  // populate your view model with values from the database
  return View(model);
}

[HttpPost]
public ActionResult Edit(StudentVM model)
{
  // save and redirect
}

请注意,我对您的模型隐含的数据库结构感到有些困惑(例如,当 null 时,为什么您需要单独的 QuestionSubjectQuestion 模型SubjectID 值将其标识为“一般”问题)。我建议您先在 GET 方法中硬编码一些值,看看它是如何工作和回发的。

StudentVM model = new StudentVM();
model.ID = 1;
model.Name = "bambiinela";
model.Subjects = new List<SubjectVM>()
{
  new SubjectVM()
  {
    Questions = new List<QuestionVM>()
    {
      new QuestionVM()
      {
        ID = 1,
        Text = "Question 1",
        SelectedAnswer = ?, // set this if you want to preselect an option
        PossibleAnswers = new List<AnswerVM>()
        {
          new AnswerVM()
          {
            ID = 1,
            Text = "Answer A"
          },
          new AnswerVM()
          {
            ID = 1,
            Text = "Answer B"
          }
        }
      },
      new QuestionVM()
      {
        ID = 2,
        Text = "Question 2",
        PossibleAnswers = new List<AnswerVM>()
        {
          // similar to above
        }
      }
    }
  },
  new SubjectVM()
  {
    ID = 1,
    Name = "Math",
    Questions = new List<QuestionVM>()
    {
      // similar to above
    }
  }
};

当您发帖时,模型会填充每个主题中每个问题的所选答案的 ID。请注意对某些属性使用 DisplayFor()。这些不会回发,因此如果您返回 View (例如 ModelState 无效),您需要重新填充这些属性。或者,您可以生成只读文本框或为这些属性添加隐藏输入。我还建议您检查生成的 HTML,特别是名称属性,它看起来像

<input type="radio" name="Subjects[0].Questions[0].SelectedAnswer" ...

让您了解集合如何在回发时绑定(bind)到您的模型

关于c# - ASP.NET MVC 5 组单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28055287/

相关文章:

javascript - 使用 javascript 使文本框可见

.net - 如何在 Linq 和 SQL 中将行转换为列

c# - Razor:在 foreach 循环中获取上一个/下一个对象属性

c# - 循环 A 列表的十进制列表

asp.net - 关于信号R中发送消息

javascript - 从 ASP.NET 调用 Javascript 函数

c# - session 变量返回 null

c# - 如何为自定义对象而不是整个模型调用 Html.Display?

c# - 不清晰的转换图像。 wmf转png

c# - 使用 json.net 反序列化静态属性?