【问题标题】:ASP.NET Core MVC : post list of list Index was out of range errorASP.NET Core MVC:列表索引的发布列表超出范围错误
【发布时间】: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


    【解决方案1】:

    您的代码中有错误

    @foreach (var question in Model)
    {
                int i = 0;
     @Html.HiddenFor(m => m[i].SurveyQuesId, new { Value = question.SurveyQuesId })
    

    对于每个项目,您将始终拥有 i=0,因为它会重复分配零。

    用for循环会好很多

    @for(var i=0; i < Model.Count; i++)
    {
     @Html.HiddenFor(m => m[i].SurveyQuesId, new { Value = @Model[i].SurveyQuesId })
    ....and so on
    

    代码中的第二个 foreach 循环也是如此。应该是

    @for (var a=0;  a < @Model[i].SurveyChoices.Count; a++)
    

    【讨论】:

    • oooh :D,我想我现在需要睡觉了,谢谢 :D
    【解决方案2】:

    你的代码有一些错误,变量ia永远不会改变。 您应该在 foreach 循环中手动处理此问题,如下所示:

    @foreach (var question in Model)
    {
       int i = 0;
       // rest of your code
       i++;
    }
    

    或者您可以使用for 循环而不是foreach

    for(int index=0;index<Model.Count;index++){...}
    

    除了这些,你可以在你的代码中省略这个 if 语句,因为当没有项目时,for 循环不会运行:

    @if (Model != null && Model.Count() > 0)
    

    或者您可以使用Any(),如下所示:

    @if (Model.Any()){...}
    

    请记住,如果您的存储中没有数据,您应该返回空列表而不是null

    【讨论】:

      猜你喜欢
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多