In MVC is it possible to override an editor templa

2019-05-30 02:56发布

问题:

is it possible to override an editor template?

I have DateTime fields in my model, which are used for arrival/departure dates - and these are rendered using the following EditorTemplate:

@model Nullable<System.DateTime> 

@if ( Model.HasValue ) { 
   @Html.TextBox( "" , String.Format( "{0:dd/MM/yyyy}" , Model.Value ) , new  { @class = "datepicker span2" } ) 
} 
else { 
   @Html.TextBox( "" , String.Format( "{0:dd/MM/yyyy}" , DateTime.Now ) , new { @class = "datepicker span2" } ) 
} 

...which will format datetime fields eg: 01/08/2012

However, I also want to show, in another field, the date AND time a booking was made eg:

22/07/2012 08:23

My model is:

    public DateTime Arrival { get; set; }
    public DateTime Departure { get; set; }
    public DateTime TimeBooked { get; set; }

I would like TimeBooked to show time as well - but the Editor Template obviously just shows the date.

Can this be overridden? Or is there another way of doing this?

Thank you,

Mark

回答1:

You can add a different named editor which shows time also and use an overload of EditorFor, which accepts template name as second parameter, like:

EditorFor(m=>m.TimeBooked, "DateWithTimeTemplate")

MSDN help



回答2:

You can by using the UIHintAttribute attribute. You can decorate the TimeBooked property with this attribute so MVC will know which editor to use.



回答3:

Yes, you can do that by adding the hh:mm placeholder..

String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now)

For more examples, see here..