简体   繁体   中英

Order dropdown list in ASP.Net mvc 5 application

I have a dropdown and I want it to appear in a particular order where dropdown option header should come before footer . but I am not able to do so.

Helper

public static readonly string HEADER_ID = "-1000";
public static readonly string FOOTER_ID = "-1001";

CSHTML

<select id="simTextEditorSelection" onchange="ShowTextEditorBasedOnSelection();"  style="float:right;">
    @foreach (PageInfoMV anItemForEditor in Model.ItemContents)
    {
        <option value="@anItemForEditor.ItemId">@anItemForEditor.ItemDisplayText</option>
    }

UI

在此处输入图片说明

PS: I don't want to change the enum values of Header and footer. Please guide me.

My Attempt:

@foreach (PageInfoMV anItemForEditor in Model.ItemContents.OrderByDescending(x=>x.Id))

But it created some other issues. So, I want to avoid it.

Assume you have this class:

public class MyClass
{
    public int Id { get; set; }
    public int Name { get; set; }
}

In the Action you can create a SelectList from any list as followed:

public ActionResult Create()
{
    var list = db.MyClass.ToList(); //or an other way to get the list of items
    //you can add som more items to the list:
    list.Add(new MyClass { Id=-1000, Name="Some Name" });
    ViewBag.Selectlist = new SelectList(list.OrderByDescending(x=>x.Id), "Id", "Name");
    return View();
}

In the View :

@{
    var optionList = ViewBag.Selectlist as SelectList;
}

@Html.DropDownListFor(model => model.someProperty, optionlist, "- Select an option -")

Change your cshtml to this and you should have your wish

<select id="simTextEditorSelection" onchange="ShowTextEditorBasedOnSelection();"  style="float:right;">
@foreach (PageInfoMV anItemForEditor in Model.ItemContents.OrderByDescending())
{
    <option value="@anItemForEditor.ItemId">@anItemForEditor.ItemDisplayText</option>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM