Add row for totals in webgrid – ASP.NET MVC

How to add sum of column at the bottom of webgrid column?
This article will show you how to add sum of column at the bottom of webgrid column. This is very common and frequently used function. also this article also show you how to add a row in webgrid using jQuery. you can add a row anywhere in between grid.

Approach: Once webgrid load on page call a function which will loop through the each row of webgrid and find out the price column perform sum of the price. finally add a row at the bottom of grid.

Add row in webgrid

Add row in webgrid

Here is code .

<script type="text/javascript">
    $(document).ready(function () {
        var total = 0;
        $('#grid .price').each(function () {
            total = total + parseFloat($(this)[0].innerHTML.toLocaleString());
        });
        $('tbody').append('<tr><td><b>Total</b></td><td><b>' + total.toFixed(2) + '</b></td></tr>');
    });
</script>

and complete code with webgrid

@model List<WebGrigColumnSum.Models.Product> 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style> .price{  } </style>

<script type="text/javascript">
    $(document).ready(function () {
        var total = 0;
        $('#grid .price').each(function () {
            total = total + parseFloat($(this)[0].innerHTML.toLocaleString());
        });
        $('tbody').append('<tr><td><b>Total</b></td><td><b>' + total.toFixed(2) + '</b></td></tr>');
    });
</script>

<h2>webgrid - Add row for total</h2>
@{
    var grid = new WebGrid(Model, defaultSort: "ProductName", rowsPerPage: 5);
}

<div id="grid" >
@grid.GetHtml(tableStyle: "table", footerStyle: "foot",
    columns:
        grid.Columns(
            grid.Column("Name", format: @<text>@item.ProductName</text>),
            grid.Column("Price", header: "Price", format: @<text>@String.Format("{0:0.00}", (decimal)(@item.Price))</text>, style: "price")))
</div>

In this approach while adding a row we are creating html string and appending it bottom of grid, but I will suggest use jQuery template to generate HTML and then append it to grid which will be more organised approach.

Advertisements
This entry was posted in ASP.NET MVC Web Grid, jQuery, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s