問題:
在ASP.NET MVC 5 應用程式中,一個表單具有多組單選按鈕。每個群組代表一個問題,但程式碼片段僅產生一個群組,導致只有第一個問題選擇了單選按鈕,而取消選擇了其他問題。如何解決這個問題,以便按問題正確分組單選按鈕?
答案:
要依問題將單選按鈕分組,需要解決所提供程式碼中的幾個問題:
修改後的程式碼:
@foreach (var question in Model.GeneralQuestions) { <div class="well"> <h3><strong>@question.QuestionString</strong></h3> @foreach (var answer in question.PossibleAnswers) { @Html.RadioButtonFor( model => model.GeneralQuestions.IndexOf(question), // Binding to index of question in list answer.Answer, new { id = $"question_{question.QuestionID}_answer_{answer.Answer}" }) @Html.Label(answer.Answer) <br /> } </div> }
檢視模型:
建立具有綁定到單選按鈕並顯示的屬性的視圖模型
public class QuestionVM { public string QuestionString { get; set; } public IEnumerable<AnswerVM> PossibleAnswers { get; set; } } public class StudentVM { public int ID { get; set; } public string Name { get; set; } public List<SubjectVM> Subjects { get; set; } } public class SubjectVM { public string Name { get; set; } public List<QuestionVM> Questions { get; set; } }
視圖:
@model 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) 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].QuestionString) foreach (var answer in Model.Subjects[i].Questions[j].PossibleAnswers) { <div> @Html.RadioButtonFor( m => m.Subjects[i].Questions[j].SelectedAnswer, answer.ID, new { id = $"question_{SubjectQuestions[i].Questions[j].ID}_answer_{answer.ID}" }) <label for="@answer.ID">@answer.Text</label> </div> } } } <input type="submit" value="save" /> }
控制器:
public ActionResult Edit(int ID) { StudentVM model = new StudentVM(); // Populate model with data from database return View(model); } [HttpPost] public ActionResult Edit(StudentVM model) { // Save and redirect return RedirectToAction("Index"); }
修改後的代碼:
以上是如何在 ASP.NET MVC 5 中以問題正確對單選按鈕進行分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!