问题描述
我创建了一个具有以下成员的DTO:
I've created a DTO with following members:
public List<Guid> QuestionIds { get; set; }
public List<Guid> AnswerIds { get; set; }
public CompetitionDTO Competition { get; set; }
我想显示一个包含几个答案的问题列表,以显示给用户,并让他们选择他/她确定的任何问题的正确答案.CompetitionDTO具有以下样式:
I wanna display a list of questions contained several answers to show for users and let them to choose the correct answers of any question that he/she is sure about. CompetitionDTO has the following style:
public class CompetitionDTO
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public IList<QuestionDTO> Questions { get; set; }
}
和QuestionDTO:
and the QuestionDTO:
public class QuestionDTO
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Category { get; set; }
public IList<AnswerDTO> Answers { get; set; }
}
public class AnswerDTO
{
public Guid Id { get; set; }
public int Order { get; set; }
public string Title { get; set; }
}
现在在剃刀视图中,我这样写:
now in razor view I written this:
@for (var i = 0; i < Model.Competition.Questions.Count; i++)
{
@Html.DisplayTextFor(x => x.Competition.Questions[i].Title)
foreach (var t in Model.Competition.Questions[i].Answers)
{
@Html.DisplayFor(c => t.Title)
@Html.RadioButtonFor(x => x.Competition.Questions[i].Answers, false, new { Model = t.Id })
}
}
但是当我将数据传递到后续操作时它不起作用,我想获得所有选择的答案以及他们的问题,我该如何解决呢?谢谢
but it doesn't work when I pass the data to post action, I want to get the all selected answers with theirs questions, How should I solve this? thanks
推荐答案
您的答案" foreach循环与您的模型无关.由于您使用单选按钮列表来回答,所以我假设每个问题只能有一个答案,因此应该更改类 QuestionDTO类
以包含接受的答案的属性
Your foreach loop for 'Answers' does not make sense in relation to your model. Since you are using a radio button list for answers, I assume there can only be one answer for each question, therefore class class QuestionDTO
should be changed to include a property for the accepted answer
public class QuestionDTO
{
...
public Guid AcceptedAnswer { get; set; }
}
然后在视图中
@for (var i = 0; i < Model.Competition.Questions.Count; i++)
{
@Html.DisplayTextFor(x => x.Competition.Questions[i].Title)
// Add a hidden input for ID property assuming you want this to post back
@Html.HiddenFor(x => x.Competition.Questions[i].ID)
foreach (var t in Model.Competition.Questions[i].Answers)
{
@Html.DisplayFor(c => t.Title)
@Html.RadioButtonFor(x => x.Competition.Questions[i].AcceptedAnswer, t.ID)
}
}
回发时,这应该为您提供 IEnumerable< QuestionDTO>
,其中设置了 ID
和 AcceptedAnswer
属性(所有其他属性除非您包含其他隐藏的输入,否则为null)
When posting back, this should give you IEnumerable<QuestionDTO>
where the ID
and AcceptedAnswer
properties are set (all other properties will be null unless you incude additional hidden inputs)
这篇关于获取MVC中单选按钮的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!