我正在尝试使用剃刀将模型中的数据添加到表中。我的问题是我想要一个 if 语句来决定 tagg 应该是什么类,但我无法让它工作。
当我添加 if 时,运行代码时出现以下错误
The foreach block is missing a closing "}" character
如何添加if语句?这是我当前的代码
@{
var counter = 0;
}
@foreach (var item in Model)
{
if(item.status == "Active") {
<tr>
}
else {
<tr class="danger">
}
<td>@counter</td>
<td>@item.FirstName @item.LastName</td>
<td>@item.Email</td>
<td>@item.PhoneNumber</td>
<td>Ändra</td>
<td>Inaktivera</td>
</tr>
counter++;
}
MVC 应该检测 html 标签并将其渲染出来,但似乎这并不总是有效。
在大括号之间,尝试添加一个标签
例如:
{
<text>
your html
</text>
}
或
如果您只是添加课程,请尝试以下操作:
<tr @(item.status == "Active" ? String.Empty : "class=\"danger\"" )>
尝试下面的代码。
@{
var counter = 0;
}
@foreach (var item in Model)
{
if(item.status == "Active") {
<text> <tr> </text>
}
else {
<text><tr class="danger"></text>
}
<td>@counter</td>
<td>@item.FirstName @item.LastName</td>
<td>@item.Email</td>
<td>@item.PhoneNumber</td>
<td>Ändra</td>
<td>Inaktivera</td>
</tr>
counter++;
}
MVC 检测 HTML 标签。所以它不会添加这样的if语句。 您也不能使用
<text><text>
。
您需要检查
<tr>
标签本身的条件。请参阅下面给出的结果。
@{
var counter = 0;
}
<table>
@foreach (var item in Model)
{
<tr @(item.status=="Active" ? String.Empty : "class=\" danger\"")>
<td>@counter</td>
<td>@item.FirstName @item.LastName</td>
<td>@item.Email</td>
<td>@item.PhoneNumber</td>
<td>Ändra</td>
<td>Inaktivera</td>
</tr>
counter++;
}
</table>
您可以根据需要添加采用 bool 或 string 的扩展方法
public static class HtmlHelpExtention
{
public static string IsChecked(this IHtmlHelper htmlHelper,bool IsCheck, string className)
{
return IsCheck? className:"";
}
}
然后在视图中使用它
<tr class="@Html.IsChecked(item.IsGift,"teal accent-3")">
使用此方法将使您能够使用多个类
Love Pandey 解决方案对我有用,但仅适用于一个类名。对于多个类名,浏览器将第二个名称解释为单独的属性。我的修改如下:
@{
var counter = 0;
}
<table>
@foreach (var item in Model)
string className = item.status=="Active" ? String.Empty : "item second-class-name";
{
<tr class="@className">
<td>@counter</td>
<td>@item.FirstName @item.LastName</td>
<td>@item.Email</td>
<td>@item.PhoneNumber</td>
<td>Ändra</td>
<td>Inaktivera</td>
</tr>
counter++;
}
</table>
一个代码块中不能使用两次标签。
如果由于此限制而遇到问题,请将第二个文本框作为字符串,然后使用 html 帮助程序显示它。
@{
int loop=0;
string HtmlBlock = "<table><tr><td style='font-weight:bold'>Lorem Text</td></tr></table>";
}
@foreach(var itemz in Mode.List){
If(loop ==3){ Html.Raw(HtmlBlock ); }
<text>itemz.Name Itemz.NIP</text>
loop++;
}