Format Date When Using DisplayFor HTML Helper RRS feed

  • Question

  • User-1580299748 posted

    Hello All,

    My development environment consists of ASP .Net Core 2.2 Razor (non-MVC), using c#

    On one of my .cshtml files I am using the following code to display information in a table:

    @Html.DisplayFor(modelItem => item.StartDate.ToLongDateString())

    StartDate is saved as a DateTime field in the database.

    According to the Microsoft Docs, .ToLongDateString() should format the date as follows:  "dddd, MMMM d, yyyy"

    However, I am getting the following error on the field:

    System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
    at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ExpressionMetadataProvider.FromLambdaExpression[TModel,TResult](Expression`1 expression, ViewDataDictionary`1 viewData, IModelMetadataProvider metadataProvider)
    at Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper`1.GetModelExplorer[TResult](Expression`1 expression)
    at Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper`1.DisplayFor[TResult](Expression`1 expression, String templateName, String htmlFieldName, Object additionalViewData)
    at Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperDisplayExtensions.DisplayFor[TModel,TResult](IHtmlHelper`1 htmlHelper, Expression`1 expression)

    Any information on how to correctly format item.StartDate would be appreciated.

    Thanks in advance for your time and help!

    Saturday, November 9, 2019 7:10 AM


  • User-1580299748 posted

    Found the solution...

    I was able to format the date in my class (.cs) file as such;

    [DisplayFormat(ApplyFormatInEditMode =true, DataFormatString = "{0:dddd, MMMM d, yyy}")]
    public DateTime StartDate { get; set; }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 9, 2019 9:51 PM