📜  mvc select list order by - C# (1)

📅  最后修改于: 2023-12-03 14:44:26.018000             🧑  作者: Mango

MVC Select List Order By - C#

Introduction

MVC Select List is an essential component in the ASP.NET MVC Framework to provide alternatives for selecting an item from a list of options. The Select List allows choosing from various options, including dropdown, checkbox, radiobutton, etc. Sometimes, we need to order the Select List based on some criteria such as date or alphabetically. In this tutorial, we will discuss how to order a Select List in MVC using C#.

Prerequisites
  • Visual Studio installed on the computer.
  • Basic knowledge of C# programming.
Steps
1. Create a Model

First, create a Model that will contain the option data. For example, we will create a simple class named User with two properties ID and Name.

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }
}
2. Create a Controller

Next, create a Controller and an action method that will create an ordered Select List using LINQ. In the following code, we have created an action method named Index that fetches a list of User objects using LINQ, orders the list by name, and offers it to the View as a list of Select List Items.

public ActionResult Index()
{
    List<User> users = new List<User>()
    {
        new User(){ ID=1, Name="John"},
        new User(){ ID=2, Name="Bob"},
        new User(){ ID=3, Name="Lisa"},
        new User(){ ID=4, Name="Alice"},
    };

    users = users.OrderBy(u => u.Name).ToList();
    
    IEnumerable<SelectListItem> selectList = 
        from user in users
        select new SelectListItem
        {
            Text = user.Name,
            Value = user.ID.ToString()
        };

    ViewBag.UserList = selectList;
        
    return View();
}
3. Create a View

Finally, create a View file that will display the Select List. In the following code, we have created a simple View file that uses the Razor syntax to render the Select List.

@{
    ViewBag.Title = "Index";
}

<h2>Ordered Select List</h2>

@Html.DropDownList("Users", ViewBag.UserList as SelectList, "Select User")

The code above creates a dropdown list with options ordered by Name.

Conclusion

In this tutorial, we have learned how to order a Select List by Name in an MVC application using C#. We created a Model, a Controller, and a View to show the Select List with ordered options to the user. We used the LINQ OrderBy method to sort the list of options and rendered it using Razor syntax.