Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Sorting the List from a data class model field in descending order

$
0
0

I was using a data class model to simplify and maximize the .NET features (I can't mention them one by one, and I'm sorry about that).

Sorting the List<string> from a data class model field in descending order doesn't work as expected.


These are the code snippets that I'm currently working with:

My data class model:

[Keyless]public class SimulateImg{  [Required]  public List<string> ImgList { get; set; } = [];}

Note that I am not using this data class model with DbSet in the meantime. Therefore, I didn't include and configure this in my DbContext.


This is how I use that data class model in my Razor page:

@page "/to-my-page"@rendermode InteractiveServer@using Microsoft.EntityFrameworkCore@using MyProject.Models.SQLServer@using MyProject.Data.SQLServer@implements IAsyncDisposable@inject IDbContextFactory<MyProject.Data.SQLServer.SQLServerContext> DbFactory@inject NavigationManager NavigationManager@inject IJSRuntime JS<div class="border rounded rounded-secondary p-3 m-2"><h5>Product</h5><EditForm Model="simulateImg" OnValidSubmit="SimulateImageList" FormName="create" Enhance><DataAnnotationsValidator /><div class="container-fluid p-0"><div class="column"><div class="col-12 col-lg-12 mb-3"><InputFile class="btn btn-outline-primary my-1" OnChange="HandleImageListUpload" accept="image/*"            multiple /><ValidationMessage For="() => simulateImg.ImgList" class="text-danger" />          @if (simulateImg.ImgList is not null)          {            @foreach (var img in simulateImg.ImgList)            {<img src="@img" class="img-thumbnail m-3" alt="Test Image" />            }          }</div></div></div><button type="submit" class="btn btn-primary">Save</button></EditForm></div><div id="liveToast" class="toast align-items-center text-bg-primary border-0 position-fixed bottom-0 end-0 mb-3 me-3"  role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="1500"><div class="d-flex"><div class="toast-body">      New records created successfully!</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"      @onclick="DisposeToastThenNavigate"></button></div></div><div id="liveToastError"  class="toast align-items-center text-bg-danger border-0 position-fixed bottom-0 end-0 mb-3 me-3" role="alert"  aria-live="assertive" aria-atomic="true" data-bs-delay="3000"><div class="d-flex"><div class="toast-body">      Someting went wrong: "@errorMessage". Please try again later.</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"      aria-label="Close"></button></div></div><script>  window.showLiveToast = () => {    const toastEl = document.getElementById('liveToast');    if (toastEl) {      const toast = bootstrap.Toast.getOrCreateInstance(toastEl);      toast.show();      toastEl.addEventListener('hidden.bs.toast', () => {        window.location.replace('/to-other-page');      });    }  };  window.showLiveToastError = () => {    const toastEl = document.getElementById('liveToastError');    if (toastEl) {      const toast = bootstrap.Toast.getOrCreateInstance(toastEl);      toast.show();    }  };</script>@code {  [SupplyParameterFromForm]  private SimulateImg simulateImg { get; set; } = new();  private SQLServerContext context = default!;  private string? output;  private string? errorMessage;  protected override void OnInitialized()  {    context = DbFactory.CreateDbContext();  }  private async Task HandleImageListUpload(InputFileChangeEventArgs e)  {    long maxAllowedSize = 3L * 1024L * 1024L; //3 MB limit    int maxFileCount = 8;    try    {      foreach (var file in e.GetMultipleFiles(maxFileCount))      {        using var readStream = file.OpenReadStream(maxAllowedSize);        using var memoryStream = new MemoryStream();        await readStream.CopyToAsync(memoryStream);        var base64 = Convert.ToBase64String(memoryStream.ToArray());        simulateImg.ImgList.Add($"data:{file.ContentType};base64,{base64}");        simulateImg.ImgList.Reverse();      }    }    catch (IOException ex)    {      errorMessage = ex.Message;      simulateImg.ImgList.Clear();      await JS.InvokeVoidAsync("showLiveToastError");    }    catch (Exception ex)    {      errorMessage = ex.Message;      simulateImg.ImgList.Clear();      await JS.InvokeVoidAsync("showLiveToastError");    }  }  private async Task SimulateImageList()  {    // This is how I save the images to the database. At the moment, it is in pending features status.  }  private void DisposeToastThenNavigate()  {    NavigationManager.NavigateTo("/to-other-page", replace: true);  }  public async ValueTask DisposeAsync() // this is important  {    await context.DisposeAsync();  }}

Note for future readers: The code has insufficient data handling, particularly in the image list collection and data validations. For example, if the user has already selected the maximum of 8 items and adds a single image, the new image should either replace the last or first item in the list, or the user should be informed that the limit is only 8 items. Unfortunately, it doesn't behave this way. I'd appreciate it if someone would consider answering this part.


On the other hand, if I test the program with this chronological order of images:

  1. Gadget_demo_image_330x330_1.png
  2. Gadget_demo_image_330x330_2.png
  3. Gadget_demo_image_330x330_3.png
  4. Gadget_demo_image_330x330_4.png
  5. Gadget_demo_image_330x330_5.png

Moreover, the file name would be discarded, and I expected the list of items to be sorted based on their original arrangement; that's the main reason why I used the numeric order of the list, instead of a bullet.

After the images were rendered on the client-side, this is the result I got:

Responsively wrapped

output

Horizontally wrapped

output

It shows that I have no problem with the front-end layout.

I was expecting the program to sort the list from 5 to 1 instead.

I've tried selecting multiple image files at once as well as one by one, but the sorting issue remains the same.

I would greatly appreciate any help!


Viewing all articles
Browse latest Browse all 4839

Trending Articles