In this article I will explain with an example, how to use Html.TextBoxFor inside ForEach Loop ASP.Net MVC Razor.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Note: The Customers Table of the Northwind Database will be used in this project.
Creating an Entity Data Model
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
Controller
The Entity Framework is now configured and hence now we can create a Controller and write code to fetch the records from the Customers Table of the Northwind Database.
Inside the Index Action method, the Top 10 Customer records are fetched and returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
return View(from customer in entities.Customers.Take(10)
select customer);
}
}
View
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
Inside ForEach Loop Customer ContactName is displayed using the Html.TextBoxFor helper method in the second column of the HTML Table.
@model IEnumerable<TextBoxFor_Loop_MVC.Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<h4>Customers</h4>
<hr/>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.CustomerID</td>
<td>@Html.TextBoxFor(m => customer.ContactName)</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads