Suppose the following model:
public class ViewBookModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
}
I'm currently rendering it like this in my Razor view:
<h1>@Model.Title</h1>
@if (Model.Subtitle != null)
{
<h2>@Model.Subtitle</h2>
}
My question is about the Subtitle
bit. The above approach feels a little clunky, and can get repetitive (which is probably a bad sign) at times.
Are there any better, less verbose, more elegant ways to handle this situation?
I had considered (a) the option now mentioned in Mat's Mug's answer, as well as (b) moving the condition to the model:
public class ViewBookModel
{
// ...
public string ShowSubtitle {
get { return string.IsNullOrEmpty(Subtitle); }
}
}
With this change to the view:
@if (Model.ShowSubtitle)
However, that doesn't address my main issue: the verbosity (i.e. 4 lines of view code just to display Subtitle
).