Set the selected value in a Selectlist (Dropdownlist)

Asked

Viewed 4,024 times

4

I have a list of vehicle models:

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

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 to 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 ai beauty, but I want to set a value, equal to HTML Selected.

  • 1

    Yes Tiago, that’s right, I decided to create a Viewbag.Selectedvalue and passing in the third parameter of the dropdown the value in the case of the ID that came from the database, which was to be selected, being thus @Html.Dropdownlist("Modeloid", new Selectlist(Viewbag.Modelslevehicles, "value", "text", Viewbag.Selectedvalue)

1 answer

3

Change the View code so you can write to the property Selected:

@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) 
    });
}
  • I can get the value of the dropdownlist by creating it at runtime ?

  • @Andreeh What execution time? At View or in the Controller?

  • Whatever, I need to pick up the selected id at the drop and do a check with it.

  • @Andreeh Yes, you can. Preferably mount to DropDown in View. All responsibility for how the information is presented is View.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.