Format date in ViewBag

1

I have a ViewBag returning two dates in a DropDown, but they are returning with the same formatting that was saved in the database (MM / dd / yyy HH: mm: ss). I need them to return in the pattern (dd / MM / yyyy).

My ViewBag looks like this:

 ViewBag.Ferias = funcionarioFeriasRepository.Lista.Where(r => r.CdMatricula == matricula && r.SqContrato == contrato && r.DtInicioConcessao != null)
               .Select(x => x.DtInicioPeriodo + " à " + x.DtFimPeriodo);

And in my view, I call it this way:

@Html.DropDownList("Ferias", new SelectList(ViewBag.Ferias, "Ferias"))

The result is this:

  

Jun 22 2010 12:00 AM to Feb 19 2014 12:00 AM

    
asked by anonymous 30.01.2015 / 17:26

2 answers

0

I managed to separate the two attributes, and concatenating them in the view. It looks like this:

Controller:

ViewBag.Ferias = funcionarioFeriasRepository.Lista.Where(r => r.CdMatricula == matricula && r.SqContrato == contrato && r.DtInicioConcessao == null)
            .Select(x => x.DtInicioPeriodo).ToList();
            ViewBag.FimFerias = funcionarioFeriasRepository.Lista.Where(r => r.CdMatricula == matricula && r.SqContrato == contrato && r.DtInicioConcessao == null)
            .Select(x => x.DtFimPeriodo).ToList();

View:

<select>
                                @foreach (var date in ViewBag.Ferias)
                                {
                                    foreach (var fim in ViewBag.FimFerias) { 
                                    <option>
                                        @Convert.ToDateTime(date).ToShortDateString() à @Convert.ToDateTime(fim).ToShortDateString()
                                    </option>
                                    }
                                }

If someone has a better alternative, please post here.                                 

    
30.01.2015 / 19:34
1

If the data is of nullable type and some argument may have a null value:

It would look like this:

ViewBag.Ferias = funcionarioFeriasRepository.Lista.Where(r => r.CdMatricula == matricula && r.SqContrato == contrato && r.DtInicioConcessao != null)
           .Select(x => 
            x.DtInicioPeriodo.HasValue ? x.Value.DtInicioPeriodo.ToString("dd/MM/yyyy") : "" 
             + " à " + 
            x.DtFimPeriodo.HasValue ? x.Value.DtFimPeriodo.ToString("dd/MM/yyyy") : "");
    
30.01.2015 / 17:49