chobo2
chobo2

Reputation: 85765

How to sort an ASP.NET MVC dropdownlist?

I have this code

    List<SelectListItem> list = new List<SelectListItem>()
    { 
        new SelectListItem() { Text = "bob", Value = "bob"},
        new SelectListItem() { Text = "apple", Value = "apple"},
        new SelectListItem() { Text = "grapes", Value = "grapes"},
    };

This will be used for binding with the asp.net mvc html helper. However I want to sort it before I bind it. How could i do this?

Upvotes: 7

Views: 29770

Answers (9)

tdman1325
tdman1325

Reputation: 240

To sort in place, use the sort function:

list.Sort((x, y) => x.Text.CompareTo(y.Text));

Upvotes: 0

michellhornung
michellhornung

Reputation: 21

A very simple way to handle it in Controller:

ViewBag.change_week = new SelectList(db.weeks.OrderBy(x=> x.week_guid), "week_guid", "week_number");

Upvotes: 0

griegs
griegs

Reputation: 22760

If you can use LINQ then:

list.OrderBy(x => x.Value)

or

list.OrderByDescending(x =>x.Value)

should do it.

edit

That should read;

list = list.OrderBy(x => x.Value);

Upvotes: 18

Red
Red

Reputation: 3267

Isn't the idea of MVC to separate function and display? What if you want to reuse the same list with different orderings?

I'd have thought this would be best as it only sorts if for the specified control.

Add a property to the Model you are using for the view:

public SelectList Fruit { get; set; }

Populate that list in your constructor (I'm using Entity Framework):

model.Fruit= new SelectList(db.tblFruit.Select(f => new { Id = f.ID, Name = f.Name }), "ID", "Name", "[Select Fruit]");

Then add your select list:

@Html.DropDownListFor(x => x.ID, new SelectList(Model.Fruit.OrderBy(y => y.Text), "Value", "Text"), "-- Select One --", new { @class = "form-control" })

Upvotes: 2

Htun Thein Win
Htun Thein Win

Reputation: 54

-------Store Procedure-----(SQL)

USE [Your Database]
GO

CRATE PROC [dbo].[GetAllDataByID]
@ID int


AS
BEGIN
        SELECT * FROM Your_Table
        WHERE ID=@ID
        ORDER BY Your_ColumnName 
END

----------Default.aspx---------

 <asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>

---------Default.aspx.cs-------

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<YourTable> table= new List<YourTable>();
                YourtableRepository tableRepo = new YourtableRepository();



                int conuntryInfoID=1;
                table= tableRepo.GetAllDataByID(ID);

                ddlYourTable.DataSource = stateInfo;
                ddlYourTable.DataTextField = "Your_ColumnName";
                ddlYourTable.DataValueField = "ID";
                ddlYourTable.DataBind();



            }
        }

-------LINQ Helper Class----

public class TableRepository
    {
        string connstr;

        public TableRepository() 
        {
            connstr = Settings.Default.YourTableConnectionString.ToString();
        }

        public List<YourTable> GetAllDataByID(int ID)
        {
            List<YourTable> table= new List<YourTable>();
            using (YourTableDBDataContext dc = new YourTableDBDataContext ())
            {
                table= dc.GetAllDataByID(CID).ToList();
            }
            return table;
        }
    }

Upvotes: -2

LukLed
LukLed

Reputation: 31842

Here you go:

List<SelectListItem> list = new List<SelectListItem>()
{ 
    new SelectListItem() { Text = "apple", Value = "apple"},
    new SelectListItem() { Text = "bob", Value = "bob"},
    new SelectListItem() { Text = "grapes", Value = "grapes"},
};

Sorted:)

Sorry, couldn't stop myself:)

EDIT

It looks as if you needed:

var fruits = new List<string> {"apple", "bob", "grapes"};
fruits.Sort();
var fruitsSelectList = new SelectList(fruits);

and then in view

Html.DropDownList("Fruit",fruitsSelectList);

Upvotes: 13

Chuckie
Chuckie

Reputation: 135

list.Sort

List<SelectListItem> list = new List<SelectListItem>() 

{ new SelectListItem() { Text = "bob", Value = "bob"},
new SelectListItem() { Text = "apple", Value = "apple"},
new SelectListItem() { Text = "grapes", Value = "grapes"}, };

list.sort;

Upvotes: -1

Hannoun Yassir
Hannoun Yassir

Reputation: 21192

you can also sort it in the client side using javascript (jquery)

BTW if you know the elements of the list just sort them yourself :

List<SelectListItem> list = new List<SelectListItem> {
 new SelectListItem { Text = "apple", Value = "apple"},
 new SelectListItem { Text = "bob", Value = "bob"}, 
 new SelectListItem { Text = "grapes", Value = "grapes"}
 };

Upvotes: 0

Josh
Josh

Reputation: 44906

var sorted = (from li in list
             orderby li.Text
             select li).ToList();

Voila!!

Upvotes: 2

Related Questions