简体   繁体   中英

How to check and convert a IEnumerable value to show in the view?

I receive data from DB in IEnumerable and show as List in View ASP.Net MVC. I want to take a specific column, that contains values something like "A" for active, "D" for Deactivated, and etc. So, I want to transform this characters in correctly string to show in the view. How to do this? I appreciate any help.

public string GetStatusPagamento(int fileCodigo)
{
  var statusPgto = _context.GetFileByFileCode(fileCodigo).Select(s => 
   s.StatusPagamento).FirstOrDefault();

  #region switch pagto
  switch (statusPgto.ToString())
  {
    case "A":
      return "Ativo";

    case "D":
      return "Ativo";

    case "E":
      return "Cancelado";

    case "M":
      return "Reembolsado";

    case "R":
      return "Ativo";

    case "X":
      return "Cancelado";

    default:
      return "Indefinido";
  } 
  #endregion
}

It was suppose to show string instead char in the view.

The solution that I found was to create another attribute called "SwitchStatusPagto" in my model that make a switch case of states and I call this attribute directly on my view.

 public string SwitchStatusPagto
    {
      get
      {
        if (!string.IsNullOrEmpty(StatusPagto))
        {
          switch (StatusPagto)
          {
            case "A":
            case "D":
            case "R":
              return "Ativo";
            case "E":
            case "X":
              return "Cancelado";
            case "M":
              return "Reembolsado";
            default:
              return StatusPagto;
          }
        }
        return string.Empty;
      }
    }

<td>@Html.DisplayFor(fr => itemRequisicao.SwitchStatusPagto)</td>

Note: "return string.Empty" was necessary to avoid null reference exception, if data is null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM