[英]Multiple radio button list, get selected values in controller
我正在研究動態的多項選擇表單生成器。 在這種情況下,該窗體可以具有帶有不同問題和選項的多個單選按鈕列表。
<strong>Question 1 </strong> <br/> <input type="radio" value=""><lable>Option1</lable> <input type="radio" value=""><lable>Option2</lable> <input type="radio" value=""><lable>Option3</lable> <input type="radio" value=""><lable>Option4</lable> <br /> <strong>Question 2 </strong> <br /> <input type="radio" value=""><lable>Option5</lable> <input type="radio" value=""><lable>Option6</lable>
我為此建模:
public class clsMain
{
public string[] selectedAnswer { get; set; }
public List<ClsQuestions> lstQuestion { get; set; }
public List<ClsOptions> lstOptions { get; set; }
}
public class ClsQuestions
{
public string question { get; set; }
}
public class ClsOptions
{
public int optionid { get; set; }
public string optionvalue { get; set; }
public string optionlable { get; set; }
}
調節器
[HttpPost]
public ActionResult FromSelectedValues(clsMain model)
{
return View();
}
視圖
@for (int i = 0; i < 2; i++){
Question @i
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer1"+i)
<label>Answer1 @i</label>
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer2"+i)
<label>Answer2 @i</label>
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer3"+i)
<label>Answer3 @i</label>
@Html.RadioButtonFor(m => m.SelectedAnswer[i], "Answer4"+i)
<label> Answer4 @i</label>
}
簡而言之,我想在控制器中獲得選定的選項。
在html文件中,您需要使用指定名稱對單選輸入進行分組。
首先,您必須更改您的問答模型以建立聯系。
public class ClsQuestions
{
// Parent ID to be referenced by children
public int ID { get; set; }
public string question { get; set; }
}
public class ClsOptions
{
// Parent question id of the option
public int QuestionID { get; set; }
public int optionid { get; set; }
public string optionvalue { get; set; }
public string optionlable { get; set; }
}
你會這樣改變你的看法
// A loop on all of the questions
@foreach(var item in lstQuestion) {
// Get list of all options that related to parent question
var options = lstOptions.Where(x => x.QuestionID == item.ID).ToList();
<strong>@(item.question)</strong>
<br/>
// Al loop on all found options of current question
@foreach(var option in options) {
// Group options by using the name property ('Question'+QuestionID)
<input type="radio" value="@(option.optionid)" name="Question@(item.ID)"><lable>@(option.optionlable)</lable>
}
<br />
}
現在,當您提交表單時,可以發送一系列選擇的選項。 這是將選定的選項發送到服務器的帖子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.