Home > Blockchain >  Index was out of range exception populating form fields
Index was out of range exception populating form fields

Time:06-09

I am building a html form using a ASP.NET Html helper. In the code example below, I am creating 5 fields which are populated by the TradeRisks list. If the list does not contain 5 items, I will encounter an “Index was out of range” exception. I would like to allow the form user to submit changes to the fields and then view the changes when they are saved. The user may not populate all fields.

I have managed to work around this problem by implementing some conditional logic, however I am unsure if this is the best approach and I think there must be a better way. Does anyone have any ideas?

@for (int i = 0; i < 5; i  )
{
    <div >
        <div >
            @Html.TextBoxFor(r => r.FormData.TradeRisks[i].Description)
        </div>
    </div>
}

CodePudding user response:

If you must use 5 textbox, the best approach is implementing some conditional logic.

If there is no need to put the 5 textbox, you could set the r.FormData.TradeRisks.Count as the for condition's limitation.

@for (int i = 0; i < r.FormData.TradeRisks.Count; i  )
{
    <div >
        <div >
            @Html.TextBoxFor(r => r.FormData.TradeRisks[i].Description)
        </div>
    </div>
}
  • Related