如何解决如何处理模型具有嵌套集合的强类型MVC3视图?
| 我有一个具有“问题”集合的模型。每个问题都有一个“ PossibleAnswers”的集合。可能的答案对象具有isAnswer属性,该属性应绑定到代表该问题的所选单选按钮(在每个问题的组中)。 我是MVC的新手,真的不确定如何构建视图,以便基于关联单选按钮的选择,发布的模型将为每个问题收集一个可能的答案,其中一个对象的isAnswer属性设置为true。组。 现在,该视图应为每个问题构建一个单选按钮组/列表,并带有该问题的可能答案集合,以表示与该问题相关的单选按钮选择。我可以在剃须刀上做嵌套循环吗?您是否使用局部?我发布模型时,MVC如何知道如何基于视图重建模型?解决方法
实际上非常简单。棘手的部分是使用索引器
namespace MvcApplication2.Controllers
{
public class QuizModel
{
public IList<QuestionModel> Questions { get; set; }
}
public class QuestionModel
{
public IList<AnswerModel> PossibleAnswers { get; set; }
}
public class AnswerModel
{
public bool IsAnswer { get; set; }
}
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(new QuizModel
{
Questions = Enumerable.Repeat(
new QuestionModel
{
PossibleAnswers = Enumerable.Repeat(new AnswerModel(),3).ToList()
},2).ToList()
});
}
[HttpPost]
public ActionResult Index(QuizModel model)
{
return View(model);
}
}}
那你的看法
@model MvcApplication2.Controllers.QuizModel
@{
View.Title = \"Index\";
Layout = \"~/Views/Shared/_Layout.cshtml\";
}
<h2>
Index</h2>
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Questions.Count; i++)
{
for (int j = 0; j < Model.Questions[i].PossibleAnswers.Count; j++)
{
<div>
@Html.EditorFor(c => Model.Questions[i].PossibleAnswers[j].IsAnswer)
</div>
}
}
<input type=\"submit\" value=\"Submit\" />
}
, 您需要的是视图中的\“ RadioButtonListFor \”,这是一个很好的示例
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。