I'm new to MVC 4 and I'm trying to figure out how to order a list that is being created by reading in from a model.
Here is the model code:
public class Files
{
[Key]
public int File_id { get; set; }
public string Original_file_name { get; set; }
public string Current_file_name { get; set; }
public string Description { get; set; }
public string File_path { get; set; }
public string File_type { get; set; }
public string File_status { get; set; }
public DateTime Expiry_date { get; set; }
//public int Uploaded_by { get; set; }
//public DateTime Uploaded_on { get; set; }
}
public class FilesContext : DbContext
{
public DbSet<Files> Files { get; set; }
}
Here is the controller code that creates the list:
return View(db.Files.ToList());
Lastly the html that writes it to screen:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Original_file_name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Current_file_name)
</td>
<td>
@Html.DisplayFor(modelItem => item.File_type)
</td>
<td>
@Html.DisplayFor(modelItem => item.File_status)
</td>
<td>
@Html.DisplayFor(modelItem => item.Expiry_date)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id=item.File_id }) |
<[email protected]("Test", "Test", new { id=item.File_id }) |-->
@Html.ActionLink("Delete", "Delete", new { id=item.File_id })
</td>
</tr>
}
Order By File Name Ascending:
db.Files.OrderBy(file => file.Original_file_name).ToList();
Order By File Name Descening:
db.Files.OrderByDescending(file => file.Original_file_name).ToList();
Multiple Order By:
db.Files.OrderBy(file => file.Original_file_name).ThenBy(file => file.Expiry_date).ToList();
You can also refer: MSDN: LINQ Sorting Operations