0

I currently have a view rendering a display page for a list of Employee entities. The values returned from the database for the Gender property are a string value of "M" or "F" for the corresponding gender. I would like to be able to show string "Male" or "Female" in the view from the corresponding property value.

I've added the following logic to the Index.cshtml which is working.

@foreach (var item in Model)
{
    <tr>
    //... various <td>'s
    @if (item.Gender == "M")
    {
        <td>Male</td>
    }
    else if (item.Gender == "F")
    {
        <td>Female</td>
    }
}

I'm trying to move this to a Display Template, but cant get it working.

I've added the following code to the Views\Shared\DisplayTemplates\Gender.cshtml:

@model System.String

@if (Model.Gender == "M")
{
    <td>Male</td>
}
else if (Model.Gender == "F")
{
    <td>Female</td>
}

What is the best way to get this working?

James P
  • 2,201
  • 2
  • 20
  • 30
  • Hi, as per my knowledge Display and Editor templates work for primitive types. eg. if you will rename your view from Gender.cshtml to String.cshtml it will work. But it will not work with non-primitive types. I wrote an article a long time back here http://www.codeproject.com/Articles/672591/Exploring-Display-and-Editor-Templates-in-ASP-NET – Anupam Singh Jul 05 '14 at 09:15

2 Answers2

2

You can add a partial view and call it like this in main view:

@foreach (var item in Model)
{
    // other tds here

    @Html.Partial("_Gender",item.Gender)
}

Create Partial view with name _Gender in the View >> Shared folder:

@model String

@{

Layout = null;
}

    @if (Model== "M")
    {
        <td>Male</td>
    }
    else if (Model == "F")
    {
        <td>Female</td>
    }

    // or

   <td>@(Model == "M" ? "Male" : "Female") </td>

It can also handle it in main view without creating partial view.

It can handle it in main view like this:

@foreach (var item in Model)
{
    <tr>
    //... various <td>'s
    <td>@(item.Gender == "M" ? "Male" : "Female") </td>
    </tr>
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

If you want it to work with a Display Template then you need to do something like this:

@foreach (var item in Model)
{
    @Html.DisplayFor(model => item.Gender)
}

and in the View Model attach the attribute:

[UIHint("Gender")]
public string Gender { get; set; }

UIHint tells MVC which Display template to use. Otherwise by convention MVC will look for one called String.chtml

Justin Ricketts
  • 236
  • 2
  • 5