要完成以下任务会有更优雅的代码:
foreach(var filter in Model.Filters)
{
if(filter.Selected)
{
<div class="crumb crumb_selected" id="@filter.ID">
@* much more html can be here *@
@filter.Title
<span class="counter">
(@filter.Count)
</span>
</div>
} else {
<div class="crumb" id="@filter.ID">
<a href="@Model.ClickUrl(Model.SelectedFilters, filter)">
@* much more html can be here but similar code as above *@
@filter.Title
<span class="counter">
(@filter.Count)
</span>
</a>
</div>
}
}
答案 0 :(得分:1)
foreach(var filter in Model.Filters)
{
<div class="crumb @(filter.Selected? "crumb_selected":string.empty)" id="@filter.ID">
@(filter.Selected? "<a href="@Model.ClickUrl(Model.SelectedFilters, filter)">" : string.empty)
@filter.Title
<span class="counter">
(@filter.Count)
</span>
</div>
}
}
基本上这只是测试filter.Selected并且是你已经拥有的更简洁的形式。我没有测试语法,只是把它写在我的头顶,所以请原谅我,如果它不编译。我不确定这更优雅,因为我不知道你对优雅的定义是什么。我以为你的意思是你更干。
答案 1 :(得分:0)
@helper MyHelper(SomeDataType filter)
{
@* much more html can be here *@
@filter.Title
<span class="counter">
(@filter.Count)
</span>
}
foreach(var filter in Model.Filters)
{
if (filter.Selected)
{
<div class="crumb crumb_selected" id="@filter.ID">
@MyHelper(filter)
</div>
} else {
<div class="crumb" id="@filter.ID">
<a href="@Model.ClickUrl(Model.SelectedFilters, filter)">
@MyHelper(filter)
</a>
</div>
}
}