Search code examples
asp.net-mvcwebgrid

Webgrid and formatting DateTime value when grid columns are built in model


I am creating a collection of WebGridColumns, adding them to my model and passing that to my razor page. I am doing this because there are a variable number of columns that are determined on the fly. This works well, but now I need to format datetime values to short date and am not sure how this can be accomplished when creating the collection of webgridcolumns.

 foreach (var datetimeitem in cols)
            {                    
                columns.Add(new WebGridColumn
                {   
                    ColumnName = datetimeitem,
                    Header = "MyHeader",
                    Format = **format item here**;

                });
            }

Any ideas?

J


Solution

  • Does your setup look something like this?

    @{
        var cols = new[] { "FirstDate", "SecondDate" };
        var columns = new List<WebGridColumn>();
    
        var grid = new WebGrid(new[]
        {
            new Entity { FirstDate = DateTime.Now, SecondDate = DateTime.Now },
            new Entity { FirstDate = DateTime.MinValue, SecondDate = DateTime.MinValue }
        });
    }
    

    If so, you can try

    @foreach (var datetimeitem in cols)
    {                    
        columns.Add(new WebGridColumn
        {   
            ColumnName = datetimeitem,
            Header = "MyHeader",
            // If item is already a date time
            Format = m => m[datetimeitem].ToShortDateString()
            // If you need to parse item as date time first
            // Format = m => DateTime.Parse(m[datetimeitem]).ToShortDateString()
        });
    }
    
    @grid.GetHtml(columns: columns)