In this article I will explain with an example, how to use Html.TextBoxFor inside ForEach Loop ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
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
The very first step is to create an ASP.Net MVC Application and connect it to the Northwind Database using Entity Framework. For more details, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example.
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
Using Html.TextBoxFor inside ForEach Loop in ASP.Net MVC
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);
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>
    <meta name="viewport" content="width=device-width"/>
    <table cellpadding="0" cellspacing="0">
        @foreach (Customer customer in Model)
                <td>@Html.TextBoxFor(m => customer.ContactName)</td>
Using Html.TextBoxFor inside ForEach Loop in ASP.Net MVC