优雅的 MVC 代码,用于可选的周围标签
本文关键字:周围 用于 标签 MVC 代码 | 更新日期: 2023-09-27 18:36:09
什么是更优雅的代码来完成以下任务:
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>
}
}
- div/span的重复HTML代码似乎是错误的代码
- CSS类规范也应该在优雅的版本中解决
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>
}
}
从本质上讲,这只是测试过滤器。选择并且是您已经拥有的更简洁的形式。我没有测试语法,只是把它写在我的头顶上,所以如果它没有编译,请原谅我。我不确定这是否更优雅,因为我不知道你对优雅的定义是什么。我以为你的意思是你更干燥。
@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>
}
}