Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC3 is it possible to have multiple EditorTemplates for the same type?

I have some DateTime fields on my MVC model classes - some which require a Date as input and others that require a Time as input - but both are DateTime properties.

Is it possible to have an EditorTemplate for DateTime that somehow produces a date picker to properties that are meant to be dates, and a time picker for properties that are meant to be times?

like image 958
Craig Shearer Avatar asked Aug 16 '11 04:08

Craig Shearer


1 Answers

Yes, here is one way:

In ~/Views/Shared/EditorTemplates (or ~/Views/Shared/DisplayTemplates, create template files that use your favourite view engine (example uses Razor/C#)

file Date.cshtml

replace this with a real date picker

file Time.cshtml

replace this with a real time picker

Then, in your model:

[UIHint("Date")]
public DateTime DateProperty { get; set; }

[UIHint("Time")]
public DateTime TimeProperty { get; set; }

The UIHint attribute name has to match the file name of your template, and UIHint is in System.ComponentModel.DataAnnotations, so you will need the appropriate using statement/assembly reference if you don't have it already.

Alternatively, use a TimeSpan to represent your times - that is what DateTime returns for its TimeOfDay property...

like image 76
Jon Avatar answered Nov 11 '22 21:11

Jon