MVC5 Razor循环索引越界问题及首次赋值后续留空需求求助
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
AdultCountinstances in the controller, you eliminate the index out-of-range error entirely. - The
i == 0condition 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

