Alphabetically Ordering a SelectList in MVC
Solution 1
thanks to Darin I was able to come up with the slightly modified solution of his which instead lead to me resolving this in the VM like so
List<Reason> reasonList = _db.Reasons.OrderBy(m=>m.Description).ToList();
ReasonList = new SelectList(reasonList, "Id", "Description");
Solution 2
You could use the OrderBy
extension method:
<%: Html.DropDownListFor(
x => x.ModelId,
new SelectList(Model.VehicleModels.OrderBy(x => x.Name), "Id", "Name"),
"-- Select a model --"
) %>
Myzifer
Strong believer in Comments with votes as it's too easy for people to down vote without allowing the user the chance to improve with constructive criticism.
Updated on April 24, 2020Comments
-
Myzifer about 4 years
Problem is my selectlist might have data(plus it's format is something like [Ford IV 200 xyx]) in it which I want to retire(by only displaying records which has a bit value of true in it's 3rd column which is also something I need to figure out how to do), big problem is if the user adds in say another Ford which would now display all the way at the bottom of the drop down it would look very messy and could even be overlooked so any ideas?
p.s. added jquery to the tags in case that was a possible solution to this since I am able to use that in this project.
Edit - For that 3rd column bit value filter here's the solution
-
Myzifer over 13 yearsslight problem, I think your using LinqToSql where as I'm using edmx as such x.ModelId for me is x.(table name which I'm storing too).(table column name which is actually recording the value) and with doing this or mixing it around there is still a problem with (x => x.Name) as it only has x.(Equals/GetHashCode/GetType/Selected/Text/ToString/Value) and since the table I tested it on only has 2 columns (Id and Description) I assume it is meant to match the column name which is to be ordered in this case Description, just in case I tried x.Text, x.Value and x.Selected and ...
-
Myzifer over 13 yearsall resulted in "DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'." that error.
-
Myzifer over 13 yearsfound out another way to do it which was in my viewmodel where I'd made the select list so ( public SelectList [assign random name so for example ModelList] { get; set; } List<[insert table name]> [insert random name for list for example modList] = db.[pluralised inserted table name used just before so if it was Model before it's Models now].OrderBy(x=>x.Description).ToList(); ModelList = new SelectList(modList, "Id" "Description"); where or not this alters how you would of answered the questions I dunno but if you fix the previous commented error or add in detail...
-
Myzifer over 13 yearsregarding this comment to your answer I'll mark your answer as correct
-
Myzifer over 13 yearsI'm guessing you don't get round to checking your old answers so I'll leave this another day before I post up the answer and set it as correct.