Home > Backend Development > C++ > How to Generate a Simple Html.DropDownListFor() in ASP.NET MVC?

How to Generate a Simple Html.DropDownListFor() in ASP.NET MVC?

Barbara Streisand
Release: 2025-01-19 06:48:13
Original
519 people have browsed it

How to Generate a Simple Html.DropDownListFor() in ASP.NET MVC?

Create a simple Html.DropDownListFor() drop-down list in ASP.NET MVC

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

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

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!

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