1

Below is the Property in my viewModel of Datetime,I want to display only date on the View, Can any one help me out in formatting this. right Now Im seeing 01/01/2010 12:00:00 AM

   public DateTime ModifiedDate
    {
        get
        {
            return Region.ModifiedDate;
        }
        set
        {
            Region.ModifiedDate = value;
        }
    }

 @Html.TextBoxFor(model => model.ModifiedDate)
TJK
  • 441
  • 4
  • 11
  • 27
  • possible duplicate of [How to render a DateTime in a specific format in ASP.NET MVC 3?](http://stackoverflow.com/questions/6001654/how-to-render-a-datetime-in-a-specific-format-in-asp-net-mvc-3) – Jon Sep 18 '11 at 02:25

2 Answers2

4

Model

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyy}" )]
public DateTime RecipeDate{ get; set; }

Edit Template

@model DateTime 
@Html.TextBox("", string.Format(ViewData.TemplateInfo.FormattedModelValue.ToString(), Model), new { @class = "date" })

EditorFor doesn't allow for custom attributes, you must use a TextBox or TextBoxFor

Brian
  • 1,845
  • 1
  • 22
  • 37
0

I created an editor template (located in the Shared\EditorTemplates folder in my solution) that looks like this:

@model System.DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty, new { @class = "date"})

And then when I want to use it,

@Html.EditorFor(model => model.RecipeDate, new { @class = "date" })
@Html.ValidationMessageFor(model => model.RecipeDate)

Seems to work pretty well for me.

itsmatt
  • 31,265
  • 10
  • 100
  • 164
  • Wouldn't you have to use @Html.EditorFor instead of @Html.TextBoxFor? – Only Bolivian Here Sep 18 '11 at 02:29
  • @Sergio - yes, that's correct. I had "TextBox" on the brain when I was typing it in since that's what the OP had in the question. I edited my answer, thanks for catching that. – itsmatt Sep 18 '11 at 02:32
  • It is working but i want to make this editor field readonly... is there any way... – TJK Sep 18 '11 at 07:54
  • tried this Html.EditorFor(model => model.ModifiedDate, new { style = "width:120px", readonly = "readonly" }) but still not working... – TJK Sep 18 '11 at 08:00