简体   繁体   中英

format datetime object inside ajax.actionlink

I have a view where there are ajax.actionlinks, some of these action links need to display a date property of the model and I have the date property as follows:

[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]

public DateTime? Date { get; set; }

however, because ajax.actionlink accepts a string for its first argument, I can't use a lambda expression :

m => m.Date

rather I'm using

Model.Date.ToString()

but this isn't showing the formatting I want. I've tried doing

Model.Date.ToString("MM-dd-yyyy");

but I'm getting red underline because its not recognizing the ToString overload with 1 argument... any ideas on how I can get this to work?

Since Model.Date is nullable, you need to access the Value of the DateTime? before using that version of ToString :

Model.Date.HasValue ? Model.Date.Value.ToString("MM-dd-yyyy") : null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM