Home > Backend Development > C++ > How to Create a Simple Drop-Down List Using Html.DropDownListFor() in ASP.NET MVC?

How to Create a Simple Drop-Down List Using Html.DropDownListFor() in ASP.NET MVC?

Patricia Arquette
Release: 2025-01-19 07:07:09
Original
328 people have browsed it

How to Create a Simple Drop-Down List Using Html.DropDownListFor() in ASP.NET MVC?

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():

  1. Get a list of options, such as a list of objects representing color names.
  2. Define a model property to represent the selected item, such as MyColorId.
  3. Use the Html.DropDownListFor helper method in the view to provide the model properties, the option list, and the option's display and value fields (for example, "ColorId" and "Name").

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

In your model, create a property that represents the selected item:

<code class="language-csharp">public class PageModel
{
    public int MyColorId { get; set; }
}</code>
Copy after login

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

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!

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