How to show a date in dd / MM / yyyy format in a view in Asp.net MVC3

Controller code

int No= Convert.ToInt32(reqCookies["NO"].ToString()); Student stud = db.Students.Single(n => n.No == No); return View(stud); 

Im transmits No after the user logs in and wants the record of this registered person to be displayed, which I successfully completed. My problem is again with the date. When a record is recorded. The user is displayed. Date of birth is displayed along with the time. Like this 2/19/2001 12:00:00 AM , instead I only want a part of the date, not a time for something like this 19/2/2001 . For this, I tried to convert the date in the format dd / MM / yyyy

 DateTime DOB=stud.DOB.tostring("dd/MM/yyyy"); 

Getting error: No overload for 'ToString ()' method takes 1 argument

The code in my view is as follows:

 <td>@Html.DisplayFor(model => model.DOB.ToString())</td> 

And when I try to change the format in the view

 <td>@Html.DisplayFor(model => model.DOB.ToString("dd/MM/yyyy"))</td> 

Getting error: No overload for 'ToString ()' method takes 1 argument

Where can I do the conversion and how to trim the time when the Part will be displayed.

+4
source share
1 answer

You can use DisplayFormat in the model to format the date:

 [DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}")] public DateTime myDate { get; set; } 

And then in the view:

 <td>@Html.DisplayFor(model => model.DOB)</td> 

Update:

Alternatively, since DisplayFor () simply displays the date without any tags, you can simply display the date without using the template helpers:

 @Model.myDate.ToString("dd/MM/yyyy") 

Or to display in a text field you can use:

 @Html.TextBox("Date", Model.myDate.ToString("dd/MM/yyyy")) 
+5
source

Source: https://habr.com/ru/post/1385837/


All Articles