Display only Date in @Html.DisplayFor() in MVC

2019-06-26 07:17发布

I work in MVC5 and EntityFramework for displaying data into View.

right now in my view data format is :- 10/22/2014 12:00:00 AM But i want only date :- 22/10/2014 in this format

i try this code but it not working

 @if (item.chekin_on_after != null)
                    { @Html.DisplayFor(modelItem => item.chekin_on_after, "ShortDateTime")}

I also follow few link in stackoverflow but not helpful Date Format using Html.DisplayFor() in MVC5, Display only date and no time

3条回答
beautiful°
2楼-- · 2019-06-26 07:41

You can use this function in your controller before populating the data to model :

public static System.DateTime ParseDate(string value, string style)
{
    DateTime blankDate = default(DateTime);
    if ((value != null & value.Length > 0)) {
        string formattedDate = Strings.Format(Convert.ToDateTime(value), style);
        return formattedDate;
    } else {
        return blankDate;
    }
}

Where value is your: 10/22/2014 12:00:00 AM and style is :"MM/dd/yyyy" or something as you want

查看更多
Rolldiameter
3楼-- · 2019-06-26 07:48

I didn’t use @html.DisplayFor().Instead of this I use

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", item.chekin_on_after))

And it works perfectly.

查看更多
▲ chillily
4楼-- · 2019-06-26 07:52

Try to use below attribute in your model class.

[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime chekin_on_after { get; set; }

Hope it helps..

查看更多
登录 后发表回答