Building a Basic HTML DropDownListFor in ASP.NET MVC 2
ASP.NET MVC offers a streamlined approach to generating HTML dropdown lists using static options. Let's create a simple dropdown with options like "Red," "Green," and "Blue."
1. Defining the Model:
First, create a Plain Old CLR Object (POCO) to represent your data. Here's a sample Color
class:
<code class="language-csharp">public class Color { public int ColorId { get; set; } public string Name { get; set; } }</code>
2. Populating the Dropdown Options:
Next, define a static list of Color
objects to populate the dropdown's options:
<code class="language-csharp">public static IEnumerable<Color> Colors = new List<Color> { new Color { ColorId = 1, Name = "Red" }, new Color { ColorId = 2, Name = "Green" }, new Color { ColorId = 3, Name = "Blue" } };</code>
3. Implementing in the View:
Finally, use the Html.DropDownListFor()
helper in your ASP.NET MVC view to render the dropdown:
<code class="language-html">@Html.DropDownListFor(model => model.MyColorId, new SelectList(Color.Colors, "ColorId", "Name"))</code>
This code generates a dropdown list using the Colors
list. The ColorId
property is used as the value, and the Name
property as the displayed text. The selected value is bound to the MyColorId
property of your model.
The above is the detailed content of How to Create a Simple HTML DropDownListFor in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!