用于可选周围标签的优雅MVC代码

时间:2012-06-04 13:07:51

标签: c# asp.net-mvc asp.net-mvc-3 razor

要完成以下任务会有更优雅的代码:

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-class规范也应该在优雅的版本中解决

2 个答案:

答案 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>
  }
}