Kamil Będkowski
Kamil Będkowski

Reputation: 1092

Displaying only Date in Razor View

In my model i have propery:

public DateTime CreatedFrom { get; set; }

In strongly typed view i what to show that date and make it editable (but only date,not time). I use:

@Html.EditorFor(m=>m.CreatedFrom.ToShortDateString())

When i want to go to that view exception occures:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

How do it correctly?

Upvotes: 2

Views: 3853

Answers (3)

linquize
linquize

Reputation: 20366

Note that definition is

Html.EditorFor<T1, T2>(Expression<T1, T2> x)

not

Html.EditorFor<T1, T2>(Func<T1, T2> f)

So the razor engine only looks for field name CreatedFrom, but cannot handle method call. May be you need additional js to help convert back and forth.

Upvotes: 1

Dangerous
Dangerous

Reputation: 4909

Linquinze is right, the EditorFor is for an Expression and not a Func.

If you are trying to display a textbox though for your date you could use:

@Html.TextBox("CreatedFrom", @Model.CreatedFrom.ToShortDateString())

which I believe will achieve the same thing.

Upvotes: 1

jim tollan
jim tollan

Reputation: 22485

kamil, you cannot bind your model to a property method, you will only be able to bind it to:

@Html.EditorFor(m=>m.CreatedFrom)

I would strongly advise that you sort out the datetime issue inside your controller (or service class) either as part of the initial HttpGet action to populate the view, or inside the HttpPost when you send the values back (not quite as desirable a scenario). Either way, the remedial action must be taken at controller level.

Upvotes: 1

Related Questions