In MVC Razor view, I am trying to format a DateTime field to display time only. Using below code I am getting error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
<td>@(Html.DisplayFor(m=>row.LastUpdatedDate.ToString("HH:mm:ss")))</td>
Any help please what is causing this error and how to fix it ?
Thanks for your help.
You have a very simple way to solve this and you might run into this problem more than once.
To understand what's happening, you are passing a method as a parameter. Instead, you should be passing an expression.
Instead of doing this
You should do
Another possible approach could be using extension methods to achieve the same. Using that approach you will not be populating your views with hard coded format.
Extension Method
View
Link: DateTime to Date in ASP.net MVC
DisplayFor expects an expression that identifies the object that contains the properties to display. It will use built in, or custom, templates to render that display. You trying to provide the display logic as that expression parameter, which is not valid.
Use
or
Instead of TextBoxFor use TextBox and specify the format in the value field i.e.
Using bootstrap datepicker this would look like:
I was having the same problem and I have resolved the problem. If you want to convert "LastUpdatedDate" to a specific format then you can try this: