【问题标题】:More streamlined way to write this if statement in cshtml在 cshtml 中编写此 if 语句的更简化方式
【发布时间】:2018-08-14 13:39:09
【问题描述】:
我只是想看看是否有更精简的方式来编写下面的if 语句?
@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>
}
【问题讨论】:
标签:
.net
asp.net-mvc
razor
【解决方案1】:
当然,是这样的:
<td><a href="Template comparisons/@(templateId).html">@(templateTitle + (templateGroupTitle != null ? (" - " + templateGroupTitle) : ""))</a></td>
或许更好
@
{
var title = templateTitle + (templateGroupTitle != null ? (" - " + templateGroupTitle) : "");
}
<td><a href="Template comparisons/@(templateId).html">@title</a></td>
也许是最好的:
@
{
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>
选择您最喜欢的方法。
我可能对括号感到困惑,但你明白了。