Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add row in webgrid

Tags:

webgrid

I'm working with MVC 3 webgrid and i need to add a new row into webgrid to show sum of price from product table.
Any ideas are appreciated.
Here's my code

@{
WebGrid grid = new WebGrid(source: Model,
                           rowsPerPage: 3,
                           canSort: true,
                           canPage: true,
                           ajaxUpdateContainerId: "ajaxgrid");  


@grid.GetHtml(
    alternatingRowStyle: "altrow",
    mode: WebGridPagerModes.All,
    firstText: "<< ",
    previousText: "< ",
    nextText: " >",
    lastText: " >>",
    columns: grid.Columns(
            grid.Column(format: (item) => new HtmlString(Html.ActionLink("Edit", "Edit", new { id = item.ProductId }).ToString() + " | " +
                                                        Html.ActionLink("Delete", "Delete", new { id = item.ProductId }).ToString()
                                                        )
                        ),
            grid.Column("ProductId", "Product Id"),
            grid.Column("CategoryId", "Category Name", format: (item) => item.Category.CategoryName),
            grid.Column("ProductName", "Product Name"),
            grid.Column("Price", "Price", format: @<text>@String.Format("{0:c}", item.Price)</text>)
    )
)

}

like image 974
lct_005 Avatar asked Feb 11 '26 20:02

lct_005


2 Answers

I had a similar problem so I created an extension of the built in MVC WebGrid. Code and example usage is at https://gist.github.com/3211605. Hopefully it's helpful.

like image 122
portlandrock Avatar answered Feb 20 '26 13:02

portlandrock


If you're okay with using JQuery and having the footer content not being column-aligned, adding a footer to a WebGrid is a bit hacky, but not difficult:

@{
  var grid = new WebGrid(...);
}
@grid.GetHtml(
  ...,
  htmlAttributes: new { id = "myTable" }
)

<span id="footerContent">This will be in footer</span>

<script>
  $().ready(function () {
    $('#footerContent').appendTo('#myTable tfoot tr td:last');
  }
</script>

The basics are:

  1. Set your table's HTML ID attribute, using the htmlAttributes parameter of WebGrid.GetHtml()
  2. Put the footer's contents in an element on your page
  3. Use JQuery's .appendTo() method to add the content element to the end of the footer's TD element

A more robust solution should make sure those elements exist, but you get the idea.

Assuming your model already contains the sum (or a method to get the sum), just build your footer like:

<span id="footerContent">@Model.Total</span>
like image 41
DaveD Avatar answered Feb 20 '26 12:02

DaveD