简体   繁体   中英

How to display a small rectangle with dynamic color in GridMVC

I have a MVC application where I am populating a grid from my model. A model property "RAG" has a string containing color name. Based on which I am populating the grid with a small colored square.

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.DMRTitle)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PlannedDate)
        </td>            
        <td>
            @if (item.RAG == "Green")
            {
                <div style="height: 20px; width: 20px; background-color: lightgreen"></div>
            }
            else if (item.RAG == "Amber")
            {
                <div style="height: 20px; width: 20px; background-color: orange"></div>
            }
            else
            {
                <div style="height: 20px; width: 20px; background-color: orangered"></div>
            }
        </td>            
    </tr>
}

This code works fine and my Grid is rendered as expected.

在此输入图像描述

Now I wanted to add SOrting and Filtering feature, so I changed my Grid to Grid.MVC.

I am able to render the columns as text using this code.

<div>
@Html.Grid(Model).Columns(columns =>
{
    columns.Add(c => c.DMRTitle).Titled("Milestone").Filterable(true).SetWidth(100);
    columns.Add(c => c.PlannedDate).Titled("Planned Date").Format("{0:dd-MMM-yyyy}").Filterable(true).SetWidth(100);        

    columns.Add(c => c.RAG).Titled("RAG").Filterable(true).SetWidth(100);


}).WithPaging(5).Sortable(true)

How Can I change the Text in the RAG column to the colored squares that I was using before?

If adding a square is not possible, then can I change the cell background color based on the value it contains? that will also work for me.

Finally I found a solution to this.

I just added the columns as this

columns.Add(c => c.RAG).Titled("RAG").Filterable(true).Sanitized(false).Encoded(false).RenderValueAs(c => new HtmlString(
    "<div style='height: 20px; width: 20px; background-color: " + GetColorForRag(c.RAG) + "'></div>"
    )).SetWidth(50);

and this is the color function

@functions
{

public string GetColorForRag(string RAG)
{
    if (RAG == "Red")
        return "Orangered";
    else if (RAG == "Amber")
        return "orange";
    else
        return "lightgreen";
}

}

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