Adding serial numbers to a list of records in an MVC application is a common requirement. It helps users to easily reference and identify records. In this article, we will walk you through how to achieve this in an ASP.NET MVC application.
Before we proceed further If you want to go through with the MVC tutorial series. Please follow this link. MVC Tutorial
Step-by-Step Guide to Add Serial Number in View Page
Step 1: Create .NET MVC application in Visual Studio 2022
Step 2: Create the Model
First, we need a model that represents the data. For this example, let’s create a Product
model.
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Step 3: Create the Controller
Next, we create a controller to manage the product list. In the ProductController
, we will fetch the list of products and pass it to the view.
public class ProductController : Controller
{
public ActionResult Index()
{
List<Product> products = GetProducts();
return View(products);
}
private List<Product> GetProducts()
{
return new List<Product>
{
new Product { ProductID = 1, Name = "Product 1", Price = 10.0M },
new Product { ProductID = 2, Name = "Product 2", Price = 20.0M },
new Product { ProductID = 3, Name = "Product 3", Price = 30.0M },
// Add more products as needed
};
}
}
Step 4: Create the View
In the view, we will display the list of products with serial numbers. We’ll use Razor syntax to iterate over the products and generate the serial numbers.
@model IEnumerable<YourNamespace.Models.Product>
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<table border="1">
<thead>
<tr>
<th>S.No</th>
<th>Product Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@if (Model != null && Model.Any())
{
int serialNumber = 1;
foreach (var product in Model)
{
<tr>
<td>@serialNumber</td>
<td>@product.Name</td>
<td>@product.Price</td>
</tr>
serialNumber++;
}
}
else
{
<tr>
<td colspan="3">No products available.</td>
</tr>
}
</tbody>
</table>
</body>
</html>
Code Explanation
- Model: The
Product
model defines the structure of our data. - Controller: The
ProductController
fetches the list of products and passes it to the view. TheGetProducts
method is a placeholder for data retrieval, which could be replaced with a database call. - View: The view iterates over the product list and assigns a serial number to each product. The serial number is generated using a simple integer counter that increments with each iteration.
By following these steps, we can add serial numbers to a list of records in an MVC application effectively.