【问题标题】:Changing html button Class from Data in Model (ASP.NET MVC)从模型中的数据更改 html 按钮类(ASP.NET MVC)
【发布时间】:2017-10-13 15:50:22
【问题描述】:

我有这个 HTML 按钮

<li><button class="btn-link glyphicon glyphicon-heart-empty" style="text-decoration:none;"></button></li>

“项目”是模型中的项目

@foreach (var Item in Model)

我正在寻找项目“项目”中的一个字段,即Item.ID

我想从

更改按钮类
class="btn-link glyphicon glyphicon-heart-empty"

到这里

class="btn glyphicon glyphicon-heart"

如果值是ID等于1

但我不想使用 IF/ELSE 语句创建额外的按钮,例如

@if (Item.ID == 0)
  {
 <li><button class="btn-link glyphicon glyphicon-heart-empty" onclick="Run(@Item.ID)"></button></li>                    
  }
  else
  {
 <li><button class="btn glyphicon glyphicon-heart" onclick="Run(@Item.ID)"></button></li>
 }

有没有更好的方法来实现这一点所以我只更改了 CLASS

干杯

【问题讨论】:

  • 你写了两次同样的东西,“从class="btn-link glyphicon glyphicon-heart-empty"class="btn-link glyphicon glyphicon-heart-empty"

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


【解决方案1】:

您可以在此处使用ternary operator

class="btn-link glyphicon @(Item.ID == 0 ? "glyphicon-heart-empty" : "glyphicon-heart")"

【讨论】:

  • 为解决方案干杯
【解决方案2】:

你也不能试试这个:

@{string glyphicon = string.empty}
@foreach (var item in Model)
{
    { glyphicon = item.Id == 0 ? "btn-link glyphicon glyphicon-heart-empty"
                               : "btn-link glyphicon glyphicon-heart";
    }

    <li>
        <button class="btn-link glyphicon @glyphicon" onclick="Run(@item.ID)"></button>
    </li> 
}

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多