Reputation: 6136
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
Upvotes: 4
Views: 1514
Reputation: 13775
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.
Upvotes: 1
Reputation: 24754
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.
Upvotes: 0