views:

42

answers:

2

Basically I have a custom built "Date" class "EndDate" in my MVC output model. FYI: The "Date" class builds of DateTime but hides the time functionality. I've created a display template for this Date type that formats the date nicely but in once instance (shown below) if the object is null (in this case for EndDate) I would like the text "No End Date Specified" output instead.

<%:Html.DisplayFor(m => m.EndDate)%>

I can't change the display template as thats common for all instances of the Date object, I don't really want to change the model itself either. Basically I want something like:

<%:Html.DisplayFor((m => (m.EndDate == null) ? "No End Date Specified" : m.EndDate)%>

Is the above possible in any form? If not, what would be a better way to implement this functionality. I guess even if there is a way to do this, if it's not a good idea please let me know why not and any better way of doing this

A: 

Do you know you can use a more specific custom template by using the Controller name in the folder structure?

You have probably created: /Shared/DisplayTemplates/CustomDate.ascx But for a specific controller you could use: /MySpecific/DisplayTemplates/CustomDate.ascx

Now you don't need to do any sort of dynamic DisplayFor calls. The issue you'll run into is that DisplayFor really really wants to know what property of what object type your model expression came from so it can lookup metadata. With a lambda like I'm pretty sure you're breaking the functionality that finds the member access and then looks up the metadata from that.

jfar
@jfar: Thanks, I am aware of the nested nature of the display templates. In this case it wouldn't help because I have a "StartDate" in the same model (which is also currently displayed using same DisplayFor).
Paul Hadfield
+1  A: 

Try using UIHint.

[UIHint("CustomDateNull")]
public CustomDate EndDate { get;set; }

Then create a CustomDateNull.ascx display template. The helpers will look for a UIHint before falling back on the Type itself.

If you can't edit the model at all, you'll have to resort to using RenderPartial and passing in your date as the model for your partial view.

Jab
@Jab: Thanks, I've had a play with that and have got it working. I also see that "DisplayFor" can take a display template name too, so I've ended up with the following which removes the need to have a UIHint in the Model<%:Html.DisplayFor(m => m.EndDate, "CustomDateNull")%>
Paul Hadfield
@Paul Hadfield Great! I hadn't seen the DisplayFor overload, but that seems like the best option.
Jab
When I come across an accepted answer with zero upvotes it blows my mind.
jfar