'Formatting DateTime in model to Date only in View
I am using ASP.NET MVC 5
. I have a date only picker in my create and edit form. In create form, its working just fine. But in edit form, it loads previously saved DateTime
as dd-MM-yyyy hh:mm:ss
. On clicking on textbox, my date picker appears with a calendar of Dec, 1899. Only if I can format my DateTime
, it will work fine.
Though, I know how to solve this problems in Struts 2, I am new to ASP.NET MVC. Can anybody please tell me how to format my DateTime
model property to Date only in my View?
Here is my model:-
public class Vehicle
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int VehicleId
{ get; set; }
[Display(Name = "Vehicle name")]
[StringLength(100)]
public String Name
{ get; set; }
[Required]
public String VehicleType
{ get; set; }
[Required]
[StringLength(20)]
[Display(Name = "Registration no.")]
public String RegNo
{ get; set; }
[DataType(DataType.Date)]
[Display(Name = "Insurance date")]
public DateTime InsuranceDate
{ get; set; }
}
Here is a part of my view:-
<div class="form-group">
@Html.LabelFor(model => model.InsuranceDate, new { @class = "control-label col-md-2" })
<div class="col-md-6 input-group date" id="datePick">
@Html.EditorFor(model => model.InsuranceDate, new { @class = "form-control", id = "datePickText", placeholder = "Enter Insurrance Date" })<span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
@Html.ValidationMessageFor(model => model.InsuranceDate)
</div>
</div>
Solution 1:[1]
You need to stablish the format in your property. You can see more information here:
Solution 2:[2]
public class AsOfdates
{
public string DisplayDate { get; set; }
private DateTime TheDate;
public DateTime DateValue { get { return TheDate.Date; } set { TheDate = value; } }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | William Mendoza |