Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can generate a DropDownListFor in a loop by creating a list of SelectListItem objects, which will contain the items for the dropdown list, and passing that list to the DropDownListFor. Here's an example code:

In the Controller:

public ActionResult Index()
{
    var items = new List<SelectListItem>();
    for (int i = 1; i <= 5; i++)
    {
        items.Add(new SelectListItem { Value = i.ToString(), Text = "Item " + i.ToString() });
    }

    ViewBag.Items = items;

    return View();
}

In the View:

@Html.DropDownListFor(m => m.SelectedValue, (List<SelectListItem>) ViewBag.Items)

This will generate a dropdown list with the items "Item 1" to "Item 5". You can customize this to fit your specific needs.