Search code examples
c#asp.net-mvcdatetimeformattingwebgrid

How to format automatically generated WebGrid date columns


I see there are a lot of answers exaplaining how to format a DateTime WebGrid column individually, but is it possible to set a WebGrid to automtically format all columns of type DateTime?

I ask because my WebGrid automatically pulls the data from my classes, so I never actually access webgrid.Column, due to the fact that I am using (an attempt at) a generic WebGrid view:

@model IEnumerable<MVCQCPage.Helpers.IGriddable>

@{
    var grid = new WebGrid(new List<object>());
    var linkPrefix = string.Empty;
    var selectable = false;

    if (Model.Count() > 0)
    {
        string[] columnNames = { };

        var firstItem = Model.First();

        linkPrefix = firstItem.RowLinkPrefix;
        columnNames = firstItem.ColumnHeaders;
        selectable = firstItem.Selectable;

        grid = new WebGrid(Model,
            rowsPerPage: 100,
            columnNames: columnNames);
    }
}
<div id="grid">
    @grid.GetHtml(
            tableStyle: "table",
            alternatingRowStyle: "alternate",
            headerStyle: "header"
        )
</div>

Where IGriddable looks like this:

public interface IGriddable
{
    string RowLinkPrefix { get; }
    string[] ColumnHeaders { get; }
    bool Selectable { get; }
}

So that each class that implements it might contain something like this:

public string[] ColumnHeaders { get; } = new string[] { "SampleNo", "QCDate", "StatusClerk", "StatusSupervisor" };
public string RowLinkPrefix { get { return $"/receiving/{Pallet.Grv.GRVNo}/{Pallet.PalletSeq}/"; } }
public bool Selectable { get; } = true;

I tried adding a Displayformatto the QCDate property, but this does not help.

Any help or advice is much appreciated, thanks!


Solution

  • I managed to work around this by amending my properties like this:

    public DateTime QCDate { get; set; }
    public string Date { get { return QCDate.ToString("dd/MM/yyyy"); } } 
    

    And changing ColumnHeaders to

    public string[] ColumnHeaders { get; } = new string[] { "SampleNo", "Date", "StatusClerk", "StatusSupervisor" };
    

    So that when this item is displayed in a grid it will now show the short date string that I needed.