Home > Backend Development > C++ > How to Create a Simple HTML DropDownListFor in ASP.NET MVC?

How to Create a Simple HTML DropDownListFor in ASP.NET MVC?

Mary-Kate Olsen
Release: 2025-01-19 06:50:10
Original
116 people have browsed it

How to Create a Simple HTML DropDownListFor in ASP.NET MVC?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template