Reputation:
I have a field in an MVC 5 C# model that maps to an SQL table. The source data is of type nvarchar(10) for the needs of others who also use the table.
In the latest iteration, the users also want to be able to sort by this column, which means that I need to convert this to a datetime value (so it can be correctly sorted) and display as a shortdate.
I know I can make this field private and create a separate public function that casts this as a date, but I was wondering if there was a more compact way I could do this all in one function. I have searched around, but not seen any examples of what I am describing. Is this even possible?
Stated another way, I want to display this as a shortdate but sort it as a date. Am I on the right track, or am I missing something?
[Required]
[StringLength(10)]
[Display(Name = "Entry Date")]
[DisplayFormat(DataFormatString="{0:d}")]
public string EntryDate { get; set; }
Upvotes: 0
Views: 398
Reputation: 218877
If the data represents a date, add a property which is a date:
public DateTime? EntryDateValue
{
get
{
DateTime dateValue;
if (DateTime.TryParse(EntryDate, out dateValue))
return dateValue;
return null;
}
set
{
// parse "value" to the string format you want
// and store it in EntryDate
}
}
Bind the view to that property instead, formatting the output with .ToString("...")
as needed, and allow the sorting to take place on the DateTime?
rather than on the string. Essentially creating a pass-through property for the application code, obscuring the backing "stringly-typed" value.
In general, it's easier to tweak the correct backing data for text display than it is to tweak the text display to act like backing data.
Upvotes: 1