Search code examples
asp.net-mvc-3c#-4.0webgridrazor-grid

Computed column on a MVC3 razor Webgrid


Here is my webgrid .I am trying to add a column "EndDate" which displays a calculated value

var grid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
    grid.Bind(Model.MyRecords, rowCount: Model.TotalRecords, autoSortAndPage: false);

    grid.Pager(WebGridPagerModes.All);
    @grid.GetHtml(htmlAttributes: new { id = "grid" },
                        columns: grid.Columns(

                        grid.Column("StartDate", "Live Date"),
                        grid.Column("EndOffsetSeconds", "End in Seconds"),
                        grid.Column("StartDate"+TimeSpan.FromSeconds("OffsetSeconds"), "Difference"),

                        grid.Column(header: "Action", format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.ID })),
                        grid.Column(format: (item) => Html.ActionLink("Copy", "CopyRecord", new { id = item.ID }))

                    ));

I want to show EndDate in place of third column .

Enddate = StartDate+TimeSpan.FromSeconds(EndOffsetSeconds)

On the 3rd column I want to show result of StartDate+TimeSpan.FromSeconds(EndOffsetSeconds)

where StartDate is of DateTime type and EndOffsetSeconds is of type Integer

Example DateTime StartDate =05/20/2012 12:15:03 int EndOffsetSeconds=124000;

How to add a computed column with a Webgrid ?

Thank you in advance


Solution

  • You can add a property to your model and do the calculation in the get method.

    class MyRecord
    {
      public DateTime StartDate {get;set;}
      public int EndOffsetSeconds {get;set;}
    
      public DateTime CalculatedEndTime
      {
        get
        {
          return StartDate + TimeSpan.FromSeconds( EndOffsetSeconds );
        }
      }
    }
    

    Then just point to the calculated property in your grid.