mvc razor foreach in view with sorted data

asp.net-mvc-4, c#, foreach, razor

Solution

The problem has something do with your query provider; perhaps it simply doesn't support ordering. Without any further information, I'd recommend this:

public IEnumerable<PercConfigEntry> GetPercConfigEntries() 
{
    var results = 
        (from g in this.context.PercConfigEntry
         where g.Key == "ConfigEntries"
         select g)
        .AsEnumerable()
        .OrderBy(g => g.ConfigName);
    return results;
}

Or in fluent syntax:

public IEnumerable<PercConfigEntry> GetPercConfigEntries() 
{
    var results = this.context.PercConfigEntry
        .Where(g => g.Key == "ConfigEntries")
        .AsEnumerable()
        .OrderBy(g => g.ConfigName);
    return results;
}

This forces the query to be executed on the provider without any ordering, then re-orders it on the client—in other words, the call to `AsEnumerable` effectively disconnects the result set from the query provider so that the `OrderBy` (or any subsequent methods) are evaluated on the client. This is probably not as efficient as allowing the provider to order it, but if the provider is doesn't support ordering, this is the only way to do it.

Problem

I'm new to MVC. I want to implement data sorting on my html page. I have a model that generated with this code: ``` public IEnumerable<PercConfigEntry> GetPercConfigEntries() { var results = from g in this.context.PercConfigEntry where g.Key == "ConfigEntries" select g; return results; } ``` And a view: ``` @model IEnumerable<PercConfigEntry> @foreach ( var config in Model ) { ... } ``` This works. But when I add "orderby" to query like this: ``` public IEnumerable<PercConfigEntry> GetPercConfigEntries() { var results = from g in this.context.PercConfigEntry where g.Key == "ConfigEntries" orderby g.ConfigName select g; return results; } ``` it throws DataServiceQueryException on foreach. What's wrong? Thanks in advance.

Original source