简体   繁体   中英

How to sort view model items in razor syntax

I'm looping through Model.Images and displaying a thumbnail gallery. I want the "main" image to always display first on the page. The "main" image is a flag/property I'm setting in the object Image . It's called IsMain and it's a boolean. I'm not sure how I can sort it in code behind or sort it in the page in razor, so that the Image with property IsMain set to true is always displayed first?

here is where I'm displaying all the images.

<ul id="sortable">
  @foreach (var image in Model.Images) {
  <li class="col-sm-6 col-md-4">

    <div class="thumbnail">
      <a class="close" href="#">×</a>
      @{ var base64 = Convert.ToBase64String(image.ImageThumbnail); var thumbSrc = String.Format("data:image/gif;base64,{0}", base64); var base64Modal = Convert.ToBase64String(image.Image); var imgSrcModal = String.Format("data:image/gif;base64,{0}", base64Modal);
      var imageId = "pop" + image.YogaSpaceImageId; var imagesourceId = "imagesource" + image.YogaSpaceImageId; }
      <a class="image" id="@imageId" href="" data-toggle="modal" data-target="#myModal">
        <img id="@imagesourceId" src="@thumbSrc" data-imagesrc="@imgSrcModal" alt="image not found" width="203" height="136" />
      </a>
      <div class="caption">
        <h3>Thumbnail label</h3>
        <p>...</p>
        <p><a href="#" class="btn btn-primary" role="button">Button</a>  <a href="#" class="btn btn-default" role="button">Button</a>
        </p>
      </div>
    </div>

  </li>
  }
</ul>

Assuming Model.Images is a List<Image> , then

images = Model.Images.OrderBy(i => i.IsMain).ToList();  // I think I got the syntax right, may have to check that.

should do it.

This can be done in the controller or the view, whichever is more appropriate to your architecture.

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