In this article I will explain with an example, how to use For Each loop for populating DropDownList using Model in ASP.Net MVC Razor.
HTML SELECT element will be created in View and a For Each loop will be executed over the Model to create and add HTML OPTION elements to the DropDownList.
The Selected Value of DropDownList is easily available using Model or using Request.Form collection, but in order to get the Selected Text, the Selected Text is copied to a Hidden Field using jQuery and then it is fetched inside Controller in ASP.Net MVC Razor.
Note: For beginners in using ADO.Net with ASP.Net MVC, please refer my article ASP.Net MVC: ADO.Net Tutorial with example.
 
 
Database
This article makes use of a table named Fruits whose schema is defined as follows.
Using For Each loop to populate DropDownList using Model in ASP.Net MVC
 
The Fruits table has the following records.
Using For Each loop to populate DropDownList using Model in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
 
 
Model
The following Model class has two properties FruitId and FruitName.
public class FruitModel
{
    public int FruitId { get; set; }
    public string FruitName { get; set; }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list collection of FruitModel class is populated.
Finally the generic list collection FruitModel class objects is returned to the View.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
Note: This example uses Model class object for capturing Form field values, for more details please refer my article ASP.Net MVC: Form Submit (Post) example.
 
When the Form is submitted, the posted values are captured through the Request.Form collection.
The values of FruitId and FruitName are fetched and are set into a TempData object which will be later displayed in View using JavaScript Alert Message Box.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        List<FruitModel> fruits = PopulateFruits();
        return View(fruits);
    }
   
    [HttpPost]
    public ActionResult Submit(FormCollection formcollection)
    {
        TempData["Message"] = "Fruit Name: " + formcollection["FruitName"];
        TempData["Message"] += "\\nFruit Id: " + formcollection["FruitId"];;
        return RedirectToAction("Index");
    }
 
    private static List<FruitModel> PopulateFruits()
    {
        List<FruitModel> fruits = new List<FruitModel>();
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = " SELECT FruitName, FruitId FROM Fruits";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        fruits.Add(new FruitModel
                        {
                            FruitName = sdr["FruitName"].ToString(),
                            FruitId = Convert.ToInt32(sdr["FruitId"])
                        });
                    }
                }
                con.Close();
            }
        }
 
        return fruits;
    }
}
 
 
View
Inside the View, in the very first line the FruitModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Submit.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The DropDownList is created using the HTML SELECT element,
For adding Items to DropDownList, a For Each loop is executed over the Model items and HTML OPTION elements are added to the DropDownList.
The Form also consists of a Hidden Field and a Submit Button.
The DropDownList has been assigned a jQuery onchange event handler, when an item is selected in the DropDownList, the Text of the selected item is copied in the Hidden Field.
When the Submit Button is clicked, the Form gets submitted and the FruitId and FruitName values are sent to the Controller.
Finally the FruitId and FruitName values of the selected Fruit are displayed using JavaScript Alert Message Box.
@using DropDownList_ForLoop_MVC.Models
@model IEnumerable<FruitModel>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Submit", "Home", FormMethod.Post))
    {
        <select id="ddlFruits" name="FruitId">
            <option value="0">Please select</option>
            @foreach (FruitModel fruit in Model)
            {
                <option value="@fruit.FruitId">@fruit.FruitName</option>
            }
        </select>
        @Html.Hidden("FruitName", null, new { @id = "hfFruitName" })
        <input type="submit" value="Submit"/>
    }
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("change", "#ddlFruits", function () {
            $("#hfFruitName").val($(this).find("option:selected").text());
        });
    </script>
    @if (TempData["Message"] != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("@TempData["Message"]");
            });
        </script>
    }
</body>
</html>
 
 
Screenshot
Using For Each loop to populate DropDownList using Model in ASP.Net MVC
 
 
Downloads