How to check object's type inside Razor view?

3.2k views Asked by At

I have a class Employee which derives from Person. I list them on index page:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Details", "Details", new { id=item.Id }) 
        </td>
    </tr>
}

How to check if item is Employee xor Person inside this loop?

For instance:

@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>
}
1

There are 1 answers

2
trashr0x On

This should do the trick:

@if (item.GetType().BaseType == typeof(Employee))
{
    //item is of type Employee
}

Update: I might have misread your "How to check if item is Employee xor Person inside this loop?" question.

A XOR, by definition, must test both values. Why would you need to do that? If an object is an Employee, then he is also (by your definition) a Person. Your flow of "If he's an Employee, pass it to EmployeeController. Else, pass it to PersonController" should work, since it's evaluating if item is an Employee first (the other way around would be a problem).

The logical and conditional operators for testing one vs both sides are:

  • & (logical AND) will test both values
  • && (conditional AND) will test the second value iff the first value is true
  • | (logical OR) will test both values
  • || (conditional OR) will test the second value iff the first value is false