Search code examples
c#asp.net-mvcrazorviewbag

Is there an OrderBy option for ViewBag


I am trying to sort the items of a ViewBag list called via ForEach.

I see that there is a Model.OrderBy option.

Is there something similar for ViewBag?

My code is as follows:

<select class="list-box tri-state" id="ParentID" name="ParentID">
    @foreach (var item in ViewBag.EmployeeList)
    {
        <option value="@item.Id">@item.FirstName @item.LastName</option>
    }
</select>

Ideally I would like the Selection list to be sorted by FirstName, LastName, but it is default sorting by Id.

How should I remedy this?


Solution

  • ViewBag is dynamic.

    So assuming it was set in the controller like

    List<Employee> employees = getEmployeeList();
    
    this.ViewBag.EmployeeList = employees;
    
    //...
    
    return View(model);
    

    In the view, cast the property to a known type collection and the extension method should then be available.

    @foreach (var item in (ViewBag.EmployeeList as List<Employee>)
        .OrderBy(_ => _.FirstName).ThenBy(_ => _.LastName)) {
          <option value="@item.Id">@item.FirstName @item.LastName</option>
    }
    

    Alternatively you can sort it in the controller before assigning it to the ViewBag as well and just have the code loop the collection in the view.

    List<Employee> employees = getEmployeeList()
        .OrderBy(_ => _.FirstName).ThenBy(_ => _.LastName)
        .ToList();
    
    this.ViewBag.EmployeeList = employees;
    
    //...