I am brand new to Blazor Server, coming from a background in ASP.NET Webforms. I have a database that stores questions and answers for an employee safety test, and Im trying to display the test questions programatically in the HTML section of my page. When debugging, I get an Index Out of Range error.
Related Code:
@code {
private List<IForkLiftPerfTestContentModel> testquestion = new List<IForkLiftPerfTestContentModel>();
protected override async Task OnInitializedAsync()
{
testquestion = await testService.GetTestQuestions();
}
When I debug testquestion , it displays data properly as shown:
When I try to display an element by zero-based index, I get Index out of Range, although Intellisense doesnt complain about my code:
<td>
@testquestion[0].Topic
</td>
Clearly Im missing something, but again I am learning Blazor. Any help is appreciated!
When your blazor page will render first time, it will not yet have awaited your async operation, it will re-render once that operation is done. Meaning on first render your testquestion
will be empty - that's why you have Index Out Of Range, so you need to handle it, say for example "if testquestion is empty - display loading"
Thanks @Nikita! That was perfect!
I wrapped the Edit Form in an if/else like this:
@if (testquestion.Count == 0)
{
<h4>Test Loading...</h4>
}
else
{ <Editform>.....</EditForm>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.