user266909
user266909

Reputation: 1873

ASP.net MVC MultiSelectList with ListBox in Razor View

I am following the blog to use ASP.Net MVC MultiSelectList in my app. I am running into

"System.ArgumentException: At least one object must implement IComparable." error.

I am using ASP.Net MVC 5.2.3. My controller has an action populates a MultiSelectList and assigns it to a ViewBag.stations variable like this:

var qryResult = DB.getPatientInfoCompleted(StationIDs);            
var theseStations = qryResult.Select(x => new
{
    StationID = x.StationID,
    StationName = x.StationName
}).Distinct().OrderBy(x => x);
ViewBag.station = new MultiSelectList(theseStations, "StationID", "StationName");

The razor view has

<td>
    @Html.DropDownList("station2", (MultiSelectList)ViewBag.stations, new { multiple = "multiple"})
</td>

<td>
    @Html.ListBox("station", (MultiSelectList)ViewBag.stations, new { @id = "lstMultiSelect", @class = "btn btn-default btn-sm dropdown-toggle menu-width" })
</td>

Thanks for your help.

Upvotes: 1

Views: 861

Answers (1)

Peter B
Peter B

Reputation: 24280

This is caused by the OrderBy(x => x) clause. Anonymous objects do not implement IComparable and thus can not be ordered.

You should probably be using OrderBy(x => x.StationName) instead.

As an alternative you can also create a class for this simple object, make it implement IComparable, while choosing an appropriate compare operation.

Update:

To define a class to replace the anonymous object, look at what was used for the anonymous object: new { StationID = ... , StationName = ... } and write a class that exactly mimics those properties (I assumed them to be int and string).

Then we make the class implement the interface IComparable<...> by adding it behind the class name. The compiler will then force us to implement the method CompareTo(...) which is the only method prescribed by the interface. For the implementation I just chose to compare a single property (StationName) that seemed relevant and good for this purpose. Our new CompareTo method can now be used by the Linq OrderBy clause.

public class MyModel : IComparable<MyModel>
{
    public int StationID { get; set; }
    public string StationName { get; set; }

    public int CompareTo(MyModel other)
    {
        return this.StationName.CompareTo(other.StationName);
    }
}

Upvotes: 1

Related Questions