简体   繁体   中英

How to order a table in a specific order based on condition of the table data in asp.net?

My Issue:

I'm looking to order a table which I have set conditions on to display by a type. For example, I have conditions which make a row green, a row red, a row blue. I'd like to order these tables so it is displayed by green rows first, blue rows second and red rows third. I'm creating the conditions by using razor c# to categorise them into their colour

My Research:

I've searched and found unrelated issues. They're trying to tell me how to order things by descending or ascending order in terms of name etc. I cannot find a way to apply it to my conditions I have created.

My Effort:

From the answer suggested:

public string BackgroundColour()
    {
        string colour = string.Empty;
        if (ExistsBothFolder && IsContentSame)
        {
            colour = "lightgreen";
        }
        else if (!HasSameContentWithAnotherFileName && !ExistsBothFolder && !IsContentSame && !IsDateModifiedSame)
        {
            colour = "lightcoral";
        }
        else if (ExistsBothFolder && !IsContentSame)
        {
            colour = "lightskyblue";
        }
        else if (HasSameContentWithAnotherFileName && !ExistsBothFolder)
        {
            colour = "orange";
        }
        return colour;
    }

In my view:

    @foreach (var fileDetail in Model.Folder1.FileDetails.OrderBy(fd => fd.BackgroundColour == "lightgreen"? 0: (fd.BackgroundColour == "lightcoral"? 1 : 2))){

    <td style="background-color: @fileDetail.BackgroundColour">

Doesn't let me use operators such as == in view to the method above? Also the razor @ in the background colour isn't recognised for some reason and asks for a proper colour.

(Had to delete the previous code since it said it wasn't properly formatted, refused to let me edit the post.)

Move all those if conditions to the model. Your view should just have

<td style="background-color: @fildeDetail.BackgroundColor">
    @if (fileDetail.IsFolder )
    {
        <img alt="ListView" src="@Url.Content("https://s27.postimg.org/3ywaao4sz/new_Folder1.png")" style="width: 20px; height: 25px;" />
    }
    else
    {
        <img alt="ListView" src="@Url.Content("http://www.clker.com/cliparts/N/K/u/R/m/8/file-icon-md.png")" style="width: 20px; height: 25px;" />
    }
    <a href="#Section1">@Html.DisplayFor(modelItem => fileDetail.Name)</a>
</td>

Then you could change the order based in the foreach or in the model itself.

@foreach(var fileDetail in Model.Folder1.FileDetails
    .OrderBy(fd => fd.BackgroundColor == "green"? 0: (fd.BackgroundColor == "red"? 1 : 2)))

Although it just looks like a code smell, relying on color to set the order.

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