"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Generate a Simple Html.DropDownListFor() in ASP.NET MVC?

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

Posted on 2025-03-22
Browse:834

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

Create a simple Html.DropDownListFor() dropdown in ASP.NET MVC

In ASP.NET MVC, it is very easy to display static options in the drop-down list. Let's see how this can be achieved.

How to create a simple Html.DropDownListFor()

To generate a basic drop-down list, you can use the Html.DropDownListFor helper method. This requires a model property to bind the selected value, and a SelectList object that represents the options to be displayed.

Example usage

Consider the following list of models and color options:

public class PageModel 
{
   public int MyColorId { get; set; }
}

public static IEnumerable Colors = new List { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a dropdown list like this:

@Html.DropDownListFor(model => model.MyColorId, new SelectList(PageModel.Colors, "ColorId", "Name"))
]

This code will generate a drop-down list with two options "Red" and "Blue". The selected value is 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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3