DropDownListFor does not display selected value

1

DropDownListFor does not display value selected.

 public static List<SelectListItem> getMesesPagamento()
    {
        List<SelectListItem> listMeses = new List<SelectListItem>();

        for (byte i = 1; i <= 12; i++)
        {
            if (i == 6) // Junho
                listMeses.Add(new SelectListItem { Text = Utilitario.getMes(i), Value = i.ToString(), Selected = true });
            else
                listMeses.Add(new SelectListItem { Text = Utilitario.getMes(i), Value = i.ToString() });
        }
        return listMeses;
    }

In View:

@Html.DropDownListFor(model => model.Pagamento_MesReferencia, Model.MesesPgto, "", htmlAttributes: new { @id = "ddlMesesPgto" })

List Type

model.Pagamento_MesReferencia é do tipo List<SelectListItem>
    
asked by anonymous 17.12.2015 / 13:42

2 answers

0

I appreciate that in the controller you put true (it was meant to work), but it did not work right here, take a look there. I did the test here and it's resolved when I do this:

 public static List<SelectListItem> getMesesPagamento()
    {
        List<SelectListItem> listMeses = new List<SelectListItem>();

        for (byte i = 1; i <= 12; i++)
        {
            if (i == 6) // Junho
                listMeses.Add(new SelectListItem { Text = Utilitario.getMes(i), Value = i.ToString(), i });
            else
                listMeses.Add(new SelectListItem { Text = Utilitario.getMes(i), Value = i.ToString() });
        }
        return listMeses;
    }

When I enter the number of the object, I do not know why with true it did not work for me either, I already had implementations that worked, if I'm not mistaken, I searched here and did not find it.     

17.12.2015 / 14:43
0

This is because you are using the wrong component. It is of no use to generate the list with Selected defined in server where the value of Pagamento_MesReferencia is not equal to 6.

The correct thing is you set the value of Pagamento_MesReferencia to an integer and mount DropDownList to View :

@Html.DropDownListFor(model => model.Pagamento_MesReferencia, Enumerable.Range(1, 12).Select(option => new SelectListItem
{
    Text = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.GetMonthName(option),
    Value = option.ToString(),
    Selected = (Model != null) && (Model.Pagamento_MesReferencia == option)
}), "Indefinido", new { @class = "form-control mes" })
    
17.12.2015 / 15:21