@Html.RadioButton для получения выбранной опции с разрешенным одиночным выбором
Я хотел бы иметь две группы радиокнопок в форме и получить проверенный элемент, избегая выбора нескольких радиокнопок, но как только я добавляю имя для ввода радиокнопок, я больше не могу видеть в своей модели, какие Товар проверен.
Вот мой взгляд:
...
@using (Html.BeginForm("Validate", "Quiz"))
{
@for (int i = 0; i < Model.questions.Count(); i++)
{
<ul>
@{ int j = 0; }
@foreach (var ch in Model.questions[i].choices)
{
<li>
@Html.RadioButtonFor(m => m.questions[i].choices[j].isChecked, true, new { id = ch.choiceId}) @ch.choiceTitle
@Html.HiddenFor(m => m.questions[i].choices[j].isChecked)
</li>
}
</ul>
}
<input type="submit" value="Valider" />
}
И вот моя структура:
public class QuizViewModel
{
public string quizTitle { get; set; }
public string quizListDisplay { get; set; }
public List<QuizQuestion> questions { get; set; }
public Guid owner { get; set; }
}
public class QuizQuestion
{
public int questionId { get; set; }
public int order { get; set; }
public string questionTitle { get; set; }
public List<QuizChoice> choices { get; set; }
public bool isSingleResponseQuestion { get; set; }
}
public class QuizChoice
{
public int choiceId { get; set; }
public string choiceTitle { get; set; }
public int index { get; set; }
public bool isCorrectAnswer { get; set; }
public bool isChecked { get; set; }
public string feedback { get; set; }
public int selectedAnswer { get; set; }
}
Но проблема в том, что я могу выбрать несколько радиокнопок в одной группе, поэтому я добавил этот код в RadioButtonFor после идентификатора:
@Name = "группа" + я
Но тогда я не смог получить isChecked в моей модели. Что я здесь не так делаю? Как решить эту проблему? Спасибо, лучшее
1 ответ
Чтобы решить эту проблему, я добавил поле selectedChoiceId в свой класс QuizQuestion и использовал RadioButtonFor следующим образом:
@ Html.RadioButtonFor (m => m.questions [i].selectedChoiceId, ch.choiceId)
1-е поле RadioButtonFor служит для группировки радиокнопок, поэтому оно должно быть одинаковым для всех радиокнопок для одного вопроса.