【发布时间】:2022-01-21 11:32:51
【问题描述】:
我需要在表单中发布对象列表,它包含另一个列表,但我收到了这个错误:
索引超出范围。必须是非负数且小于集合的大小
我的模型类:
public class SurveyQuestionDto
{
public SurveyQuestionDto()
{
SurveyChoices = new List<SurveyChoiceDto>();
}
public int SurveyQuesId { get; set; }
public DateTime? DateStart { get; set; }
public DateTime? DateEnd { get; set; }
[Required(ErrorMessage = "Required")]
public short ChoicesType { get; set; }
[StringLength(500, ErrorMessage = "MaxLength")]
public string TextAnswer { get; set; }
public virtual List<SurveyChoiceDto> SurveyChoices { get; set; }
}
public class SurveyChoiceDto
{
[Required(ErrorMessage = "Required")]
public int? LanguageId { get; set; }
[Required(ErrorMessage = "Required"),
StringLength(200, ErrorMessage = "MaxLength")]
public string Title { get; set; }
public long ChoiceId { get; set; }
public int SurveyQuesId { get; set; }
public long Count { get; set; }
public bool MarkedToDelete { get; set; }
public bool IsSelected { get; set; }
}
我的看法:
@model List<SurveyQuestionDto>
@if (Model != null && Model.Count() > 0)
{
<form action="@Url.Action("Answer", "Survey", new { typeId })" method="post" class="form form-horizontal" enctype="multipart/form-data">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@foreach (var question in Model)
{
int i = 0;
@Html.HiddenFor(m => m[i].SurveyQuesId, new { Value = question.SurveyQuesId })
<div style="background:#cccccc; padding:20px; margin:20px;">
<h2>@question.Title</h2>
@if (question.ChoicesType == (int)ChoicesTypeEnum.Text)
{
@Html.TextAreaFor(m => m[i].TextAnswer, new Dictionary<string, object> { { "data-val", "true" }, { "data-val-required", _loc["Required"] } })
}
else
{
<ul style="list-style-type:none;">
@foreach (var choice in question.SurveyChoices)
{
int a = 0;
<li>
@Html.HiddenFor(m => m[i].SurveyChoices[a].ChoiceId, new { Value = choice.ChoiceId })
@if (question.ChoicesType == (int)ChoicesTypeEnum.SingleChoice)
{
@Html.RadioButtonFor(m => m[i].SurveyChoices[a].IsSelected, null, new Dictionary<string, object> { { "data-val", "true" }, { "data-val-required", _loc["Required"] } })
}
else
{
@Html.CheckBoxFor(m => m[i].SurveyChoices[a].IsSelected, new Dictionary<string, object> { { "data-val", "true" }, { "data-val-required", _loc["Required"] } })
}
<label>@choice.Title</label>
</li>
a++;
}
</ul>
}
</div>
i++;
}
<button type="submit">Submit now</button>
</form>
}
模型对象已经有了它的值:
public async Task<IActionResult> Index(int id)
{
return View(await _rep.GetSurveyQuestionsWithChoices(id));
}
问题从这行代码开始
m[i].SurveyChoices[a].ChoiceId
有什么想法吗?
【问题讨论】:
标签: c# .net-core asp.net-core-mvc