我正在尝试在表单上创建一个选择列表。我正在使用Razors Html.DropDownListFor,但我不确定如何使用我的模型中的适当值正确填充我的DropDownList。
for (int i = 0; i < Model.Questions.Count(); i++)
{
for (int j = 0; j < Model.Questions[i].Options.Count(); j++)
{
@Html.DropDownListFor(m=>m.Questions[i].Options[j].IsSelected, ????)
}
}
模型:
public class QuestionViewModel
{
public int? Id { get; set; }
public string QuestionType { get; set; }
public string SubType { get; set; }
public string Text { get; set; }
public int SortOrder { get; set; }
public bool IsHidden { get; set; }
public List<QuestionOptionViewModel> Options { get; set; }
}
public class QuestionOptionViewModel
{
public int? Id { get; set; }
public string Text { get; set; }
public string Value { get; set; }
public bool IsChecked { get; set; }
public int Selected { get; set; }
}
答案 0 :(得分:1)
检查以下解决方案。我略微改变了你的模型 -
public class QuestionMainModel
{
public List<QuestionViewModel> Questions { get; set; }
}
public class QuestionViewModel
{
public int? Id { get; set; }
public string Text { get; set; }
public List<QuestionOptionViewModel> Options { get; set; }
public int Selected { get; set; }
}
public class QuestionOptionViewModel
{
public int? Id { get; set; }
public string Text { get; set; }
public string Value { get; set; }
}
填充视图的控制器操作 -
public ActionResult Index()
{
QuestionMainModel model = new QuestionMainModel();
List<QuestionOptionViewModel> options = new List<QuestionOptionViewModel>();
options.Add(new QuestionOptionViewModel(){ Id = 1, Text = "Ans1", Value = "1"});
options.Add(new QuestionOptionViewModel(){ Id = 2, Text = "Ans2", Value = "2"});
options.Add(new QuestionOptionViewModel(){ Id = 3, Text = "Ans3", Value = "3"});
model.Questions = new List<QuestionViewModel>();
model.Questions.Add(new QuestionViewModel() { Id = 1, Text = "Question1", Options = options });
return View(model);
}
正在显示的视图如下 -
@model MVC.Controllers.QuestionMainModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Submit", "sample", FormMethod.Post))
{
for (int i = 0; i < Model.Questions.Count; i++)
{
@Html.HiddenFor(m => m.Questions[i].Id)
@Html.LabelFor(m => m.Questions[i].Text, Model.Questions[i].Text)
@Html.DropDownListFor(m => m.Questions[i].Selected, new SelectList(Model.Questions[i].Options, "Value", "Text"), "Select an option")
}
<input type="submit" value="Click" />
}
当您点击提交按钮时,它会点击控制器操作 -
public ActionResult Submit(QuestionMainModel model)
{
return null;
}
所选答案如下 -
注意:如果您想发布所有选项和问题文本,请使用HiddenFields,就像我为Is所做的那样。
答案 1 :(得分:0)
您可以尝试以下方法:
for (int i = 0; i < Model.Questions.Count(); i++)
{
@Html.DropDownListFor(m =>
m.Questions[i].Id,
new SelectList(
m.Questions[i].Options,
"Text",
"Value",
m.Questions[i].Options.SingleOrDefault(x = > x.IsChecked).Value))
}
但请记住,您应该只有一个将IsChecked标志设置为true的选项。否则您将收到错误。