Ask Your Question
2

How can a DropDownListFor be generated in a loop?

asked 2021-12-03 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-11-24 23:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-03 11:00:00 +0000

Seen: 16 times

Last updated: Nov 24 '22