Having a little bit of trouble figuring out using a ternary with Razor view engine.
My model has a string property. If that string property is null, I want to render null in the view. If the property is not null, I want it to render the property value with a leading and trailing '.
How can I do this?
UPDATE: Sorry, changed question slightly.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You should just be able to use a ternary operator like the title suggests:
@(string.IsNullOrEmpty(Model.Prop) ? "null" : "'" + Model.Prop + "'")
Method 2
Assume you have an entity named Test with the First and Last properties:
public class Test {
public string First { get; set; }
public string Last { get; set; }
}
You can use DisplayFormat.DataFormatString and DisplayFormat.NullDisplayText to achieve your purpose:
public class Test {
[Display(Name = "First Name")]
[DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "'null'")]
public string First { get; set; }
[Display(Name = "Last Name")]
[DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "'null'")]
public string Last { get; set; }
}
AND in view:
@Html.DisplayFor(model => model.First) @Html.DisplayFor(model => model.Last)
I change the answer too:
[DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "null")]
Method 3
Ternary, loops, C# and stuff makes views ugly.
That’s what view models are exactly designed to do:
public class MyViewModel
{
[DisplayFormat(NullDisplayText = "null", DataFormatString = "'{0}'"]
public string MyProperty { get; set; }
}
and then in your strongly typed view simply:
@model MyViewModel ... @Html.DisplayFor(x => x.MyProperty)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0