-1

Can I use a for loop to show the model view list? Or do I have to use foreach?

If yes, can anyone show me an example please? Thank you.

@model IList<TestMVC1.Models.Account>
@{
    ViewBag.Title = "Index";
}
<h2>Accounts List</h2>
@{var student = ViewBag.AccoutList; }
@for (int i = 0; i < student.Count; i++)
{
    <div>@student[i].CounterID</div>
    <div>@student[i].AccountID</div>
    <div>@student[i].AccountName</div>
}
@foreach (var item in Model)
{
    <div>@item.CounterID</div>
    <div>@item.AccountID</div>
    <div>@item.AccountName</div>
}

I want to use it with for loop not foreach but it's not working! I mean the model not the viewBag

@for (int i = 0; i < Model.Count ; i++)
{
    <div>@model[i].CounterID</div>
    <div>@model[i].AccountID</div>
    <div>@model[i].AccountName</div>
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • why in `ViewBag` when you have a model? `ViewBag.AccoutList;` where is that misspelled added to ViewBag? and if this is not a part of the question why have it here? – Mark Schultheiss Apr 12 '20 at 12:47
  • Does this answer your question? [ASP.NET MVC 4 - for loop posts model collection properties but foreach does not](https://stackoverflow.com/questions/14165632/asp-net-mvc-4-for-loop-posts-model-collection-properties-but-foreach-does-not) – Mark Schultheiss Apr 12 '20 at 13:11

1 Answers1

0

You must use the @model to define the type of model in top of view file.

But if you want to access the data you should use Model or @Model.

Change the @model to @Model

@for (int i = 0; i < Model.Count ; i++)
{
    <div>@Model[i].CounterID</div>
    <div>@Model[i].AccountID</div>
    <div>@Model[i].AccountName</div>
}
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
  • 1
    `IList` is a decendent of `ICollection` which has a `Count` property https://learn.microsoft.com/en-us/dotnet/api/system.collections.icollection?view=netcore-3.1 – Mark Schultheiss Apr 12 '20 at 13:03