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?

1
  • 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 codeproject.com/Articles/672591/… Commented Jul 5, 2014 at 9:15

2 Answers 2

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>
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick reply, but I was hoping this might be possible using a DisplayTemplate?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.