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.
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
Asked: 2021-12-03 11:00:00 +0000
Seen: 16 times
Last updated: Nov 24 '22
How can dote be eliminated from the menu items in HTML?
How can resetting a list be avoided during a loop?
Is the Nextflow channel processing only the first item in the channel?
How can the contents of a list be grouped together?
What is the method to obtain the number of items in a selection?
Can you assist in transforming a set of items into a dictionary and exhibiting it?
Can two items be embedded inline in Discord.js?
What is the process of adding items to an array in a Vue 3 cart without generating duplicates?