Webgrid Date and Time Format

I am struggling with syntactic gremlins using WebGrid. In my usual razor markup, I format the date inside my foreach, e.g.

<td>
        @String.Format("{0:MM/dd/yy hh:mm:ss}", item.complianceedatetime)
    </td>

and I set the column width so

<th width="150px">
        Download Date/Time
    </th>

How do I do this with the Grid.Column syntax

grid.Column("complianceedatetime", "Download Date/Time", ?, ?)
+5
source share
4 answers
@grid.GetHtml(
    column: grid.Columns(
              grid.Column("Complianceedatetime", "Download Date / Time", 
format: @<text>@item.complianceedatetime.ToString("MM/dd/yy hh:mm:ss")</text>)
            )
)

I know this works because I have this exact code in my project:

grid.Column(
            "PublishDate",
            canSort: true,
            format: @<text>@item.PublishDate.ToString("MM/dd/yyyy")</text>
        ),
+8
source

If the DateTimeProperty is defined as (may contain null):

public DateTime? WorkedDate { get; set; }

Use this format:

grid.Column("WorkedDate", "Last Worked On",
   format: (item) => item.WorkedDate != null 
   ? item.WorkedDate.ToString("MM/dd/yy") : "", canSort: true)

Otherwise, if it is defined below (cannot be null), it will have either the actual date or the .MinDatedefault value.

public DateTime WorkedDate { get; set; }

Use format:

grid.Column("WorkedDate", "Last Worked On",
   format: (item) => item.WorkedDate != DateTime.MinValue ? 
   item.WorkedDate.ToString("MM/dd/yy") : "", canSort: true)
+3

:

@grid.GetHtml(
    column: grid.Columns(
              grid.Column("Complianceedatetime", "Download Date / Time", format: (item) => string.Format("{0:MM/dd/yy hh:mm:ss}", item.complianceedatetime)
            )
)
+1

    @grid.GetHtml(
        column: grid.Columns(
                  grid.Column ("Complianceedatetime", "Download Date / Time", 
                  format: @@ String.Format ("{0: g}", complianceedatetime))
                )
    )
0
source

All Articles