3
I possess 2 foreachs
, to search for dates on ViewBags
, where I return both in a select.
But for each item of the first foreach, it makes a complete loop in the second, thus doubling the values, for each item of the first.
Ex: If I have 3 items in the first foreach
and 2 items in the second, my final result will be 6 items in my select
, and it repeats the data, after the loop of the first.
My problem is: How to do not repeat this data?
My Foreahcs in the view:
<div class="col-md-9">
<select class="form-control" style="width:250px" id="selectPeriodo" name="sAquisitivo">
@foreach (var date in ViewBag.Ferias)
{
foreach (var fim in ViewBag.FimFerias)
{
<option>
@Convert.ToDateTime(date).ToShortDateString() à @Convert.ToDateTime(fim).ToShortDateString()
</option>
}
}
</select>
</div>
My Viewbags:
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();
Entity:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? dtInicioFerias { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? dtFimFerias { get; set; }
public string sAquisitivo { get; set; }
Upshot:
Remembering that I am working with Foreachs, because it was the only option I could find to format the dates to the dd/MM/yyyy format. Because they in a Dropdownlist were not formatted, even using toString() and adding annotations in the model.
I’ve tried it this way, but when I put it to Convert at Viewbag, I get this error: LINQ to Entities does not recognize the method 'System.String Toshortdatestring()' method, and this method cannot be Translated into a store Expression. I edited the question, with the entity.
– Randrade
If this is just the problem, it would just change the conversion place again, I will edit. I’m finding the whole expression strange, but if you’re saying it works, okay. Like I said, I can’t test it. I don’t understand why I should catch a guy
DateTime
has to be converted toDateTime
. And I don’t understand why it works on view but not in the viewbag. But your problem was having two loops. This problem has been solved.– Maniero