我的问题和答案动态填充的列表。
两个问题:
- 这些问题和答案回发后不显示
- 所选择的答案是失踪
视图模型
public class RegistrationViewModel : RegisterExternalLoginModel
{
//...etc...
public Question Question { get; set; }
public Answer Answer { get; set; }
public List<Question> Questions { get; set; }
public IList<Answer> PossibleAnswers { get; set; }
public List<SelectedAnswer> SelectedAnswers { get; set; }
public IList<SelectedAnswer> PreviousAnswers
{
set
{
foreach(Question q in Questions)
{
q.SelectedAnswers = value.Where(t => t.questionId == q.objectId).ToList() ;
}
}
}
}
选择的答案
public Answer SelectedAnswer
{
get
{
if (SelectedAnswers != null && SelectedAnswers.Count > 0)
{
var answers = SelectedAnswers.Where(t => t.questionId == objectId);
if (answers.Count() == 1)
{
var result = Answers.Where(t => t.objectId == answers.First().answerId).First();
return result;
}
}
return null;
}
}
的ActionResult
public ActionResult CreateQuestions()
{
RegistrationViewModel vm = new RegistrationViewModel();
IQFacade facade = new QFacade(CreateUserContext(true));
//Questions and Answers
vm.Questions = facade.GetQuestions().ToList();
vm.PossibleAnswers = facade.GetPossibleAnswers();
return View(vm);
}
岗位
[HttpPost]
public ActionResult CreateQuestions(RegistrationViewModel vm)
{
var context = CreateUserContext(true);
try{
IQFacade f = new QFacade(context);
f.CreateSomething(vm.User.name, vm.etc, vm.SelectedAnswers);//Need all the answers here, but null
}
catch (Exception ex)
{
//error stuff, etc...
return View(vm);//the questions do not appear after this point. Do I need to bind them again from GetQuestions or shouldn't they still be a part of the vm object that I am returning?
}
}
return RedirectToAction("Index");
}
在意见中,我使用的编辑器模板
@Html.EditorFor(x => x.Questions)
模板
@foreach (var possibleAnswer in Model.Answers)
{
<div class="radio">
@Html.RadioButtonFor(question => question.SelectedAnswer, possibleAnswer.objectId, new { id = possibleAnswer.objectId })
<label for="@possibleAnswer.objectId">@possibleAnswer.text <span>@possibleAnswer.value</span></label> <p>@possibleAnswer.description</p>
</div>
}
一切工作的第一次,但不是回发后。 我已经经历了几十个类似的SO职位的阅读。 我在想什么?