Define the selected value in a SelectList (DropDownList)

3

I have a list of vehicle models:

 private List<ModeloRastreador> modelo = new List<ModeloRastreador>();

I add the result that came from the bank

foreach (var m in modelo)
{
    modeloRastreador.Add(new SelectListItem { 
        Text = m.Nome, 
        Value = Convert.ToString(m.ID) 
    });
}

Step into my viewbag

 ViewBag.ModelosVeiculos = modeloVeiculos;

and for the dropdown

@Html.DropDownList("ModeloID", new SelectList(ViewBag.ModelosVeiculos, "value", "text"),
new { 
    style = "width:280px", 
    @class = "form-control form-control-last", 
    @id = "ModeloID" 
})

Up to that, but I want to set a value, equal to the selected HTML.

    
asked by anonymous 14.10.2014 / 17:05

1 answer

2

Change the View code so that you can type in the Selected property:

@Html.DropDownListFor(m => m.ModeloID, ((IEnumerable<SelectListItem>)ViewBag.ModelosVeiculos)
.Select(option => new SelectListItem {
    Text = option.Text,
    Value = option.Value,
    Selected = (Model != null) && (Model.ModeloID == Convert.ToInt32(option.ModeloID)
)}, "Escolha...", new 
{ 
    style = "width:280px", 
    @class = "form-control form-control-last", 
    @id = "ModeloID" 
})

Or change the code in the Controller (this example would be for a Edit ):

foreach (var m in modelo)
{
    modeloRastreador.Add(new SelectListItem { 
        Text = m.Nome, 
        Value = Convert.ToString(m.ID),
        Selected = (m.ID == modelSelecionado.ModeloID) 
    });
}
    
14.10.2014 / 19:19