Mark
Mark

Reputation: 315

MVC OrderBy EditorFor IEnumerable

I have just registered, and this is my first post, so please bear with me if the question is not the best. I have had a look about and can't find an answer that suits my requirements; this is possibly because it's not possible to achieve what I want.

I have a partial view which pulls through an IEnumerable list of EditorFor fields from a viewmodel:

@model DocumentViewModelContainer
@Html.EditorFor(m => m.Document.Metadata)

The DocumentViewModelContainer has the following code:

public class DocumentViewModelContainer
{
    public DocumentViewModel Document
    {
        get;
        set;
    }

The DocumentViewModel has the following code:

public class DocumentViewModel
{
    public IEnumerable<DocumentMetadataFieldViewModel> Metadata
        {
            get;
            set;
        }
}

There's a ton of other objects in both view models that I've left out as being irrelevant in this question. The DocumentMetadataFieldViewModel is made up of several fields of standard types (int, strings etc.)

What I'm trying to achieve is adding an OrderBy to this list pulled back by ordering by an object in the bottom view model, such as follows:

@model DocumentViewModelContainer
@Html.EditorFor(m => m.Document.Metadata.OrderBy(i => i.InstanceFieldOrder))

However this gives the error:

System.InvalidOperationException : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

I'm not only very new to MVC, but to C# in general; this project has had me learning the language on the fly, so please play nice :)

Thanks,

Mark

Upvotes: 2

Views: 1720

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039288

You should do this ordering in your controller action which is responsible to retrieve your view models and pass them to the view.

You could always perform the following horror in your view:

@model DocumentViewModelContainer
@{
    Model.Document.Metadata = Document.Metadata.OrderBy(i => i.InstanceFieldOrder).ToList();
}
@Html.EditorFor(m => m.Document.Metadata)

but promise me you won't do that.

Upvotes: 5

Related Questions