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!
Model View Controller (MVC) MVC is a design pattern used to decouple user-interface (view), data (model), and application logic (controller). This pattern helps to achieve separation of concerns.
Note that the entire ASP.NET MVC library is now obsolete.
They are the same thing. C# is the language you have used to do your development, but ASP.NET MVC is the framework you used to do it.
It's really difficult to try and learn an entirely new language/framework under pressure. If you're required to deliver working software for your day job, trying to learn ASP.NET Core at the same time might be heaping too much pressure on yourself.
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:
(Customer.MailingAddress ?? new MailingAddress()).City ?? string.Empty
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With