Jefferson
Jefferson

Reputation: 93

More streamlined way to write this if statement in cshtml

I just wanted to see if there is a more streamlined way to write this if statement below?

                    @if (templateGroupTitle != null)
                    {
                        var templateTitleCourse = @templateTitle + " - " + @templateGroupTitle;
                        <td><a href="Template comparisons/@(templateId).html">@templateTitleCourse</a></td>

                    }
                    else
                    {
                        <td><a href="Template comparisons/@(templateId).html">@templateTitle</a></td>
                    }

Upvotes: 0

Views: 41

Answers (1)

Yurii N.
Yurii N.

Reputation: 5703

Sure, something like this:

<td><a href="Template comparisons/@(templateId).html">@(templateTitle + (templateGroupTitle != null ? (" - " + templateGroupTitle) : ""))</a></td>

Or maybe even better

@
{
    var title = templateTitle + (templateGroupTitle != null ? (" - " + templateGroupTitle) : "");
}

<td><a href="Template comparisons/@(templateId).html">@title</a></td>

And maybe the best:

@
{
    var delimiter = " - ";
    var title = string.Join(delimiter, templateTitle, templateGroupTitle).TrimEnd(delimiter.ToCharArray());
    // var title = $"{templateTitle}{delimiter}{templateGroupTitle}".TrimEnd(delimiter.ToCharArray()); // Another way
}

<td><a href="Template comparisons/@(templateId).html">@title</a></td>

Choose which method do you prefer the most.

I might be confused with brackets, but you got the idea.

Upvotes: 2

Related Questions