Abdul Ahmad
Abdul Ahmad

Reputation: 10021

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?

Upvotes: 0

Views: 228

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

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;

Upvotes: 2

Related Questions