In this article I will explain with an example, how to use Html.TextBoxFor inside ForEach Loop ASP.Net MVC Razor.
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.
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)
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.
Layout = null;
<meta name="viewport" content="width=device-width"/>
<table cellpadding="0" cellspacing="0">
@foreach (Customer customer in Model)
<td>@Html.TextBoxFor(m => customer.ContactName)</td>