You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC5 Razor循环索引越界问题及首次赋值后续留空需求求助

Fixing Two MVC5 Issues: Index Out of Range & First-Loop Value Population

Hey there, let's break down your two problems and fix them up—they're both rooted in how you're initializing and accessing your attendee collection.

1. Fixing the System.ArgumentOutOfRangeException Error

This error is straightforward: your view loops through Model.AdultCount times, but in your controller, you only add one getAttendeeList object to the getAttendeeLists collection. When AdultCount is greater than 1, the second loop tries to access getAttendeeLists[1] which doesn't exist (the collection only has an element at index 0), hence the out-of-range exception.

Updated Controller Code

You need to initialize the collection with exactly AdultCount number of objects—populating the first one with user data, and leaving the rest empty:

eventattendee.AdultCount = model.AdultCount;
eventattendee.AttendeeCount = model.eventattendee();

var listOfAttndees = new List<getAttendeeList>();

// Create the correct number of attendee objects
for (int i = 0; i < eventattendee.AdultCount; i++)
{
    var lstAttendees = new getAttendeeList();
    
    // Only fill data for the first attendee
    if (i == 0)
    {
        lstAttendees.FirstName = userInfo.FirstName;
        lstAttendees.LastName = userInfo.LastName;
        lstAttendees.CellPhone = Helpers.CommonUtils.RemovePhoneFormat(phoneDetail.PhoneNumber);
        lstAttendees.Email = userInfo.EmailAddress;
    }
    
    listOfAttndees.Add(lstAttendees);
}

eventattendee.getAttendeeLists = listOfAttndees;
return View(eventattendee);

This fixes the index error by making sure the collection length matches AdultCount, and also implements your "first loop has values, rest are empty" requirement in one go.

2. Minor View Optimization

Your view logic is mostly solid, but we can tweak the null check to avoid potential null reference issues:

@if (Model != null && Model.AdultCount > 0) { <!-- Check for Model != null first -->
    for (int i = 0; i < Model.AdultCount; i++) {
        @Html.HiddenFor(m=>m.isAdult)
        <div id="div_@i">
            <h2>Adult @(i + 1) </h2>
            
            <!-- Keep your existing form field code here -->
            <div class="form-group">
                @Html.LabelFor(model => model.getAttendeeLists[i].FirstName, new { @class = "control-label col-md-2" })
                <div class="col-md-6">
                    @Html.EditorFor(model => model.getAttendeeLists[i].FirstName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.getAttendeeLists[i].FirstName, "", new { @class = "text-danger" })
                </div>
            </div>
            
            <!-- Repeat for LastName, CellPhone, Email fields -->
        </div>
    }
}

Key Takeaways

  • By looping to create AdultCount instances in the controller, you eliminate the index out-of-range error entirely.
  • The i == 0 condition ensures only the first attendee gets pre-filled with user data, while the rest stay empty—exactly the behavior you wanted.

内容的提问来源于stack exchange,提问作者Enrique Gil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:56:41