我需要使用表单创建一个视图,其中每个RadioButton
的{{1}}组TextBox
。然后,我希望Model
填充TextBox
中的值和所选RadioButton
的值。我遇到的问题是,我无法将对应的值发送给选定的RadioButton
TextBox
。
看起来像这样
有我的模型
public class CertainAnswersViewModel
{
public int SelectedValue { get; set; }
public string TextAnswer { get; set; }
public bool IsInput { get; set; }
public List<CertainAnswer> CertainAnswers { get; set; }
}
视图的
@using MY_BUKEP.Areas.Survey.Models;
@model CertainAnswersViewModel
@using (Html.BeginForm())
{
foreach (var answer in Model.CertainAnswers)
{
@Html.RadioButtonFor(m => m.SelectedValue, answer.IdOption, new { id = "" })
@Html.TextBoxFor(m => m.TextAnswer);
<br />
}
<input type="submit" />
}
Controller
中有两种方法[HttpGet]
public ViewResult Test()
{
CertainAnswer ca1 = new CertainAnswer() { IdOption = 1 };
CertainAnswer ca2 = new CertainAnswer() { IdOption = 2 };
CertainAnswersViewModel cavm = new CertainAnswersViewModel();
cavm.CertainAnswers = new List<CertainAnswer>();
cavm.CertainAnswers.Add(ca1);
cavm.CertainAnswers.Add(ca2);
return View("TestView", cavm);
}
[HttpPost]
public void Test(CertainAnswersViewModel cavm)
{
Answer a = new Answer();
a.val = cavm.TextAnswer;
a.idOption = cavm.SelectedValue;
}
答案 0 :(得分:1)
您当前的实现是为同一属性创建重复的文本框,当您提交表单时,只会绑定第一个文本框的值(如果用户要选择第3个选项并填写相关的文本框,则值为TextAnswer
将为null
,因为与第二个选项关联的文本框为空。此外,您的模型无法生成您在第二个图像中显示的视图,因为每个CertainAnswer
属性也是需要一个值来指示是否需要关联的文本框(我假设某些选项可能不是)。
你的模型需要(不是我更改了一些类和属性名称以更好地描述它们代表的内容)
public class PossibleAnswerVM
{
public int ID { get; set; }
public string Description { get; set; }
public bool RequireAdditionalText { get; set; }
}
public class QuestionVM
{
public int ID { get; set; }
public string Description { get; set; }
[Required(ErrorMesage = "Please select an option")]
public int SelectedAnswer { get; set; }
public string AdditionalText { get; set; }
public IEnumerable<PossibleAnswer> PossibleAnswers { get; set; }
}
和控制器中的代码
QuestionVM model = new QuestionVM()
{
ID = 1,
Description = "If you could return to the past, what would you choose?",
PossibleAnswers = new List<PossibleAnswer>()
{
new PossibleAnswer(){ ID = 1, Description = "Apply to another university" },
new PossibleAnswer(){ ID = 2, Description = "Apply to the same ...", RequireAdditionalText = true }
}
};
return View(model);
和视图
@model QuestionVM
@using (Html.BeginForm())
{
@Html.HiddenFor(m => m.Question.ID)
@Html.DisplayFor(m => m.Question.Description)
foreach(var option in Model.PossibleAnswers)
{
<label>
@Html.RadioButtonFor(m => m.SelectedAnswer, option.ID, new { id = "" data_textrequired = option.RequireAdditionalText })
<span>@option.Description</span>
</label>
}
@Html.ValidationMessageFor(m => m.SelectedAnswer)
@Html.TextBoxFor(m => m.AdditionalText)
<input type="submit" value="Save" />
}
请注意,添加了data-textrequired
,以便您可以使用javascript根据所选选项显示/隐藏文本框。如有必要,您还可以使用javascript将文本框定位在所选选项旁边