In ASP.NET MVC, displaying static options in a drop-down list is very simple. Let's see how to achieve this.
How to create a simple Html.DropDownListFor()
To generate a basic dropdown list, you can use the Html.DropDownListFor helper method. This requires a model property to bind the selected value, and a SelectList object representing the options to display.
Example usage
Consider the following list of models and color options:
<code class="language-csharp">public class PageModel { public int MyColorId { get; set; } } public static IEnumerable<Color> Colors = new List<Color> { new Color { ColorId = 1, Name = "Red" }, new Color { ColorId = 2, Name = "Blue" } };</code>
In your view you can create a dropdown like this:
<code class="language-html">@Html.DropDownListFor(model => model.MyColorId, new SelectList(PageModel.Colors, "ColorId", "Name"))</code>
This code will generate a dropdown list with two options "Red" and "Blue". The selected value will be bound to the MyColorId property in the model.
More information
For more information about Html.DropDownListFor, see the MSDN documentation. Additionally, you can find usage examples on Stack Overflow.
The above is the detailed content of How to Generate a Simple Html.DropDownListFor() in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!