How to change the colour of an MVC webgrid row text depending on some condition

9.4k views Asked by At

I'm new to MVC, kindly guide me. I need to change the text color of webgrid row based on conditions. As stated I'm new to MVC so I'm not sure where to start and handle this.

Below is the View

@model  IEnumerable<GridViewMVC.Models.Employee>

@{
ViewBag.Title = "Home Page";
WebGrid grid = new WebGrid(Model);
}


<div>
@grid.GetHtml(
    tableStyle:"GridTable",
    headerStyle :"GridHeader",
    footerStyle :"GridFooter",
    alternatingRowStyle :"GridAlterRow",
    rowStyle:"gridRow",        

    columns:grid.Columns(
    grid.Column("Id","Emp Id"),
    grid.Column("Name","Name"),
    grid.Column("Age","Age"),
    grid.Column("Designation","Title"),
    grid.Column("Gender","Gender")
))

</div>

in model the properties are declared. And in controller I am passing the Employee List object to view

output comes in this way

Emp Id   Name           Age   Designation   Gender
1        Anurag         24    SE             Male
2        Mike           31    Lead           Male
3        George         41    GPM            Male

Now I want to highlight the background color of Age as per this condition. If age is in between 20 to 30, the background color should be Green. If age is in between 30 to 40, the background color should be Yellow. If age is in between 40 above, the background color of that cell should be Red.

1

There are 1 answers

3
Florian Schmidinger On BEST ANSWER

Try to put this right under your @grid.Html()

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    $('tr').each(function (index) { //iterate over all table rows
        if (index > 0) {     //skip header
            if ($(this).children('td:nth-child(3)').text() < 31)  //look for the 3rd td in each row. thats where your age is.
            {
                $(this).children('td:nth-child(3)').css("background-color","green");
            }
            else if ($(this).children('td:nth-child(3)').text() < 41)
            {
                $(this).children('td:nth-child(3)').css("background-color", "yellow");
            }
            else 
            {
                $(this).children('td:nth-child(3)').css("background-color", "red");
            }
        }
    });
</script>

since the webgrid produces nothing more than a html-table