user4221591
user4221591

Reputation: 2150

defining the integer value retrieved from database

I am using data format as 1 for male, 2 for female and 3 for undefined GENDER in my database. How can I assign these values in my view i.e. for 1 show MALE , for 2 show FEMALE and for 3 show UNDEFINED? It is possible to do it from sql code but how can I do this from my view or controller?

Also I want to highlight the rows which have gender as undefined. How can I do this?

controller block

public ActionResult Display()
        {            
            return View(db.P_GET_USER().ToList());
        }

view block

@model IEnumerable<final.Models.P_GET_USER_Result>

@{
    ViewBag.Title = "Display";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Display</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.USERNAME)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.NAME)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.GENDER)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.STATUS)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CREATED_DATE)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.USERNAME)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.NAME)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.GENDER)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.STATUS)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CREATED_DATE)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

Upvotes: 0

Views: 75

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

A quick dirty approach would be to put the conditional code in your view. Another way can be to add a helper method in your view to do that:

@helper GetGender(int gender)
{
   string genderText = "";
    switch (gender)
    {
      case 1:
        genderText = "Male";
        break;
      case 2:
        genderText = "Female";
      case 3:
        genderText = "Undefined";
        break;
      default;
        break;

     return genderText;
   }

}

and then use it like:

<td>
   @GetGender(item.Gender)
</td>

More better would be to move this at some common place and reuse it in each view where needed.

A more better than above would be to have a view model which returns the respected text based on the Gender property value in your view and the view would be strongly typed with that view model and will just display it.

Upvotes: 1

Related Questions