我有一个来自Employee
的课程Person
。我将它们列在索引页面上:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Details", "Details", new { id=item.Id })
</td>
</tr>
}
如何在此循环中检查项目是否为Employee
xor Person
?
例如:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@if(**item is Employee**){
@Html.ActionLink("Details", "Details", "EmployeeController", new { id = item.Id},null)
}else{
@Html.ActionLink("Details", "Details","PersonController", new { id=item.Id }, null)
}
</td>
</tr>
}
答案 0 :(得分:3)
这应该可以解决问题:
@if (item.GetType().BaseType == typeof(Employee))
{
//item is of type Employee
}
更新:我可能误读了您的“如何检查项目是否为此循环中的员工xor人员?”问题。
根据定义,XOR
必须测试这两个值。你为什么要这么做?如果对象是Employee
,那么他(根据您的定义)也是Person
。您"If he's an Employee, pass it to EmployeeController. Else, pass it to PersonController"
的流量应该有效,因为它首先评估item
是否为Employee
(反过来会出现问题)。
测试一方与双方的逻辑和条件运算符是:
&
(logical AND
)将测试两个值&&
(conditional AND
)将测试第二个值iff
,第一个值为true
|
(logical OR
)将测试两个值||
(conditional OR
)将测试第二个值iff
,第一个值为false