Reputation: 815
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?
Upvotes: 3
Views: 1168
Reputation: 7012
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?'.
Upvotes: 3
Reputation:
You can do something like this using Html.TextBox
instead of using Html.TextBoxFor
.
@Html.TextBox("Birth date", String.Format("{0:dd/MM/yyyy}", Model.Birthdate))
Upvotes: 2
Reputation: 1939
DatePicker from jQuery is a better approach to receive date input from user. It is particularly helpful to avoid various date format confusion.
Upvotes: 0