Using Html.DropDownListFor() in ASP.NET MVC
In ASP.NET MVC, it is very easy to create a simple drop-down list with static options.
Write a simple Html.DropDownListFor():
Example:
Consider the following example data:
<code class="language-csharp">public static IEnumerable<Color> Colors = new List<Color> { new Color { ColorId = 1, Name = "Red" }, new Color { ColorId = 2, Name = "Blue" } };</code>
In your model, create a property that represents the selected item:
<code class="language-csharp">public class PageModel { public int MyColorId { get; set; } }</code>
In your view, create a dropdown using the following code:
<code class="language-html">@Html.DropDownListFor(model => model.MyColorId, new SelectList(Colors, "ColorId", "Name"))</code>
This will generate a dropdown list with "Red" and "Blue" options, and the selected value will be stored in the model's MyColorId property.
The above is the detailed content of How to Create a Simple Drop-Down List Using Html.DropDownListFor() in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!