我的asp.net mvc-5 Web应用程序中有2个模型: -
public partial class Anwer
{
public Anwer()
{
this.UserFormsAnswers = new HashSet<UserFormsAnswer>();
}
public int Id { get; set; }
public string AnwerDesc { get; set; }
public int QuestionID { get; set; }
public bool Correct { get; set; }
public virtual Question Question { get; set; }
public virtual ICollection<UserFormsAnswer> UserFormsAnswers { get; set; }
}
public partial class Question
{
public Question()
{
this.Anwers = new HashSet<Anwer>();
}
public int Id { get; set; }
public string QuestionDesc { get; set; }
public int Order { get; set; }
public bool Active { get; set; }
public virtual ICollection<Anwer> Anwers { get; set; }
}
现在我想在视图中显示所有问题,并在每个问题中用单选按钮显示其答案,所以我尝试了以下内容: -
@model IEnumerable<QuestionsDemo.Models.Question>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@{int i = 0;
foreach (var item in Model)
{
<div class="form-group">
@(i+1) <spn>-</spn> @Html.DisplayFor(modelItem => item.QuestionDesc) <br />
@foreach (var answer in item.Anwers)
{
<div class="col-md-10">
@Html.RadioButtonFor(modelitem2 => answer.QuestionID, answer.Id) @answer.AnwerDesc <br />
</div>
}
</div><hr/>
}
}
</div>
}
我认为问题的所有答案'单选按钮都会有相同的名称。因此用户只能为每个问题选择一个选项。但似乎所有答案的单选按钮都有如下名称: -
<input id="answer_QuestionID" name="answer.QuestionID" type="radio" value="1" /> 10 <br />
任何人都可以这样做吗?我如何按每个问题对单选按钮进行分组?
第二个问题。我如何能够将所有答案ID发回我的帖子操作方法?我应该使用索引器吗?答案 0 :(得分:1)
您无法使用foreach
循环生成Question
的表单控件。您需要使用for
循环,或者更好的自定义EditorTemplate
用于Question
类型。有关详细说明,请参阅Post an HTML Table to ADO.NET DataTable。
您的Question
模型还需要一个属性来绑定选定的Answer
,例如
public class Question
{
public int Id { get; set; }
....
public int SelectedAnswer { get; set; }
}
请注意您的编辑数据,因此您应该为Question
和Answer
创建视图模型,而不是在视图中使用数据模型。
使用以下代码
创建部分视图Views/Shared/EditorTemplates/QuestionVM.cshtml
@model QuestionsDemo.Models.Question
@Html.HiddenFor(m => m.Id)
// Add additional hidden inputs for any properties of Question that you want to be posted
@Html.DisplayFor(m => m.QuestionDesc)
@foreach(var answer in Model.Anwers)
{
<label>
@Html.RadioButtonFor(m => m.SelectedAnswer, answer.Id, new { id = "" })
<span>@answer.AnwerDesc</span>
</label>
}
然后主视图将是
@model IEnumerable<QuestionsDemo.Models.Question>
....
@using (Html.BeginForm())
{
....
@Html.EditorFor(m => m)
<input type="submit" value="Save" />
}
注意EditorFor()
方法将为集合中的每个项目正确生成html。