1

I am working in MVC Core using EntityFramework. How can I get the row number in view in the table?

My model is:

public class Provider{

        public int ProviderId { get; set; }
        public string Name { get; set; }
        public int DateOfBirth{ get; set; }
}

Controller is:

public async Task<IActionResult> Index()
        {
            return View(await _context.Provider.ToListAsync());
        }

View Is:

@model IEnumerable<Project.Provider>
 @foreach (var item in Model) {
                  <tr>
                <td>
                        #
                </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProviderId)
              
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.DateOfBirth)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.DateOfBirth)
             </td>
    }

output:

100 | Foo | 10/10/1990|
101 | Bar | 10/10/1990|

I want a row number at the start, output like:

1|100 | Foo | 10/10/1990|
2|101 | Bar | 10/10/1990|
jps
  • 20,041
  • 15
  • 75
  • 79
Ali Imran
  • 646
  • 1
  • 9
  • 26

1 Answers1

3

Assuming you just want to have row numbers for your table, you can do it simply by changing your view to the following:

@{
    ViewBag.Title = "Your Title";
    Layout = "~/Views/Shared/_Layout.cshtml";
    int rowNumber = 1;
}
@model IEnumerable<Project.Provider>
@foreach (var item in Model)
{
        <tr>
            <td>
                @rowNumber
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProviderId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.DateOfBirth)
            </td>
        </tr>
        rowNumber++;
}

or if you want to do it with Linq, check out this question: LINQ: Add RowNumber Column

cnndlc
  • 58
  • 7