Search code examples
javascriptjquerycssasp.net-mvcwebgrid

Mvc webgrid sort clears DOM


I've got script and style thats applied dynamically to column values in the webgrid. Everything works fine until I sort a column and thats when classes or styles are removed. I've tried my code in the _layout as well as the view..

<script type="text/javascript">
    $(document).ready(function () {            
        $("#tblWebGrid tr:not(:first)").each(function () {               
            var aptStatus = $(this).find("td:nth-child(9)").html();             
            if (aptStatus == 'Scheduled') {                   
                $(this).find("td:nth-child(9)").addClass("clsGreen");
            } else {                   
                $(this).find("td:nth-child(9)").addClass("clsRed");
            }
        });
    });     
</script>

<style type="text/css">
.clsGreen
{
    color: Green;
    font: bold 1em Arial, Helvetica, sans-serif;
    text-align: center;
    font-weight: bolder;
    margin: 0 auto;
    width: auto;
}
.clsRed
{ 
    color: Red;
    font: bold 1em Arial, Helvetica, sans-serif;
    text-align: center;
    font-weight: bolder;
    margin:0 auto;
    width:auto;
}

How do I reload the DOM and/or prevent my style from being stripped from the dynamic tags?


Solution

  • You can wrap the code that applies the styles in a separate function, and then pass the name of the function to the WebGrid's ajaxUpdateCallback parameter:

    <script>
        function styleGrid(){
        $("#tblWebGrid tr:not(:first)").each(function () {               
                var aptStatus = $(this).find("td:nth-child(9)").html();             
                if (aptStatus == 'Scheduled') {                   
                    $(this).find("td:nth-child(9)").addClass("clsGreen");
                } else {                   
                    $(this).find("td:nth-child(9)").addClass("clsRed");
                }
            });
        }
        $(document).ready(function(){
            styleGrid();
        })
    </script>
    

    Then in your Razor block:

    var grid = new WebGrid(data, ajaxUpdateCallback: "styleGrid");