views:

205

answers:

2

Hi,

I have a DateTime field in my Model. If I try to use this field in a strong typed partial view this way

<%= Html.TextBoxFor(model => model.DataUdienza.ToString("dd/MM/yyyy"), new { style = "width: 120px" })  %>

I will get the following compilation error at runtime

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

Anyway if I use it removing the formatting, ToString("dd/MM/yyyy"), everything works but the field is formatted using the time part which I dont need at all.

Where I am doing wrong? Which is the correct way to handle this?

thanks for helping!

EDIT

This is the property declaration in the model class

[Required]
[DisplayName("Data Udienza")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DataUdienza { get; set; }
A: 
<%= Html.EditorFor(model => model.DataUdienza) %>

And in your model:

[DisplayFormat(ApplyFormatInEditMode = true, 
               DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DataUdienza { get; set; }

The drawback with EditorFor is that you cannot apply custom html attributes to the generated field. As an alternative you could use the TextBox helper:

<%= Html.TextBox("DataUdienza", Model.Date.ToString("dd/MM/yyyy"), new { style = "width: 120px" })%>
Darin Dimitrov
Wow! Superfast. Thank you :) I'm gonna try it. But, in the meanwhile, how does this work if the field is a Nullable type?
Lorenzo
Works the same for nullable types.
Darin Dimitrov
I have tried to apply your solution but unfortunately does'nt work. I am gonna edit the post to add the model property declaration for your information.
Lorenzo
@Lorenzo, did you notice that `Html.EditorFor` should be used instead of `Html.TextBoxFor`?
Darin Dimitrov
@Darin: I have never used the EditorFor before. Anyway please consider that the two attributes (DataType and DisplayFormat) have been added now for trying your suggestion.
Lorenzo
+1  A: 

Create an editor template called DateTime.aspx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), ViewData) %>

Put it in your Views/Shared/EditorTemplates folder. Now when you call:

<%= Html.EditorFor(model => model.DataUdienza) %>

Your DateTime will be formatted without the time.

This will happen with all DateTimes called this way, though...

Custom html attributes can be used in this way:

<%= Html.EditorFor(model => model.DataUdienza, new {customAttr = "custom", @class = "class"}) %>

It passes through to the EditorTemplate as ViewData.

JungleFreak