Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with DateTime, it appears with 00:00:00

I have my database which has a DateTime type for Birthdate value when I register the user.

When I receive my data back, to edit the register form, I have my Razor like this:

@Html.TextBoxFor(model => model.Birthdate)

The date shows like this: 28/05/1983 00:00:00

I want only the birthdate, obviously. In my Controller, I have this:

User userset = db.User.Find(id);
return View(userset);

Very simple... Could anyone help me to solve that?

like image 602
Rubia Gardini Avatar asked Apr 15 '26 18:04

Rubia Gardini


1 Answers

Set the DisplayFormat data annotation above the property in your model.

public class User
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
    public DateTime Birthdate { get; set; }

    ...
}

Then instead of using @Html.TextBoxFor(..) use @Html.EditorFor(...).

See the DisplayFormatAttribute MSDN page for more details.

If you have generated your data model using EF you can simply create a meta class for your class to apply data annotations. For example, if my db file is called MyDB.edmx, create a buddy class file called MyDB.cs. Then inside there, I would extend the User class by attaching a metadata class to it and specifying the data annotation in the metaclass:

[MetadataType(typeof(UserMetaData))]
public partial class User{ }

public class UserMetaData
{
   [DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
   public DateTime Birthdate { get; set; }
}

See Scott Gu's post on validation, mainly the section 'But what if we are using a graphical tool for our ORM mappings?'.

like image 85
dnatoli Avatar answered Apr 18 '26 11:04

dnatoli