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?
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?'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With