简体   繁体   中英

Umbraco Razor orderby numeric property

I have a property in an Umbraco document type of numeric called position (see below).

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
  var results = CurrentPage.Children(); 
}

@foreach(var result in results.OrderBy("position"))
{
  @result.position
}

I am expecting to see 1, 2, 3, 4 ... 11, 12...

However, I am actually seeing 1, 11, 12, 2, 3, 4...

The position property is set as numeric in Umbraco, but I cannot seem to alter the order to be integer-based rather than string-based.

Any ideas on where I am going wrong?

It's actually working as expected. Although your field is a numeric field, any values accessed via a dynamic property like CurrentPage will be treated as a string value (if it exists).

You can call:

@using umbraco.MacroEngines
@inherits UmbracoTemplatePage

@{
    var results = ((DynamicNodeList)this.CurrentPage.ChildrenAsList);

    foreach(var result in results.OrderBy(x => x.Position())
    {
        ...
    }
}

This converts the children into a strongly typed list object that you can then perform LINQ against.

Update:

You could also use this provided you are using a later version:

@inherits UmbracoTemplatePage

@{
    var results = this.Model.Content.Children;

    foreach(var result in results.OrderBy(x => x.Position())
    {
        ...
    }
}

This is because to numbers are being ordered by the first #, hence the 1, 11, 12, 2, 3, 4... You can try adding a padding to the left of the position, if your not to worried about loosing the dynamic properties, you can try the following;

@{
    var results = Model.Content.Children();  

    foreach(var result in results.OrderBy(x => x.position.ToString().PadLeft(3,'0')))
    {
        @result.GetPropertyValue("position")
    } 
}

Pad Left >>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM