Consider the following code that I’m using when displaying a Customer’s mailing address inside a table in a view:
<%: Customer.MailingAddress == null ? "" : Customer.MailingAddress.City %>
I find myself using a fair amount of these ternary conditional statements and I am wondering if there is a way to refer back to the object being evaluated in the condition so that I can use it in the expression. Something like this, perhaps:
<%: Customer.MailingAddress == null ? "" : {0}.City %>
Does something like this exist? I know I can create a variable to hold the value but it would be nice to keep everything inside one tight little statement in the view pages.
Thanks!
No, there is not a way to do precisely what you’re asking without creating a variable or duplicating yourself, though you can do something like this:
This presumes that a new MailingAddress will have it’s city property / field null by default.
The last null coalescence can be removed if creating a new MailingAddress initializes the city field / property to empty string.
But this isn’t actually shorter, and it’s more hackish (in my opinion), and almost certainly less performant.