how to set a default value of 0 in dropdownlist

1

then the dropdown brings the following values

VALOR1
VALOR2
VALOR3

I want the combo to bring a default value to tell me to choose your example option:

-- SELECCIONE --
VALOR1
VALOR2
VALOR3

because it always brings me by default VALOR1

Controller

ViewBag.VBPais = new SelectList(db.Pais, "IdPais", "Nombre");

View

@Html.DropDownList("VBPais")

Testing with SelectListItem

Attempt by @Einer

    
asked by 24.01.2018 в 16:31
source

4 answers

2

Due to my own experience, I suggest you always

 @Html.DropDownList("IdPais", null, "Seleccione un país", htmlAttributes: new { @class = "form-control" })
    
answered by 24.01.2018 / 21:32
source
8

First you have to convert the country type to List<SelectListItem> to be able to display the data in SelectListItem :

// lo convertimos a lista
var paises = db.Pais.Select(x=> new SelectListItem{ Text = x.Nombre, Value = x.Id}).ToList();

Then insert an element at the beginning of the list that will have the text you expect using the Insert :

// insertamos el elemento en la primera posicion:
pais.Insert(0, new SelectListItem{ Text = "-- SELECCIONE --", Value = "0" });

And then continue with what you already have:

ViewBag.VBPais = pais;

And in your view:

@Html.DropDownList("VBPais", (IEnumerable<SelectListItem>)ViewBag.VBPais);
    
answered by 24.01.2018 в 16:43
5

try adding the following parameters:

@Html.DropDownList("VBPais", null, "Seleccione un país")
    
answered by 24.01.2018 в 16:46
2

It's very simple, with no need to add options to your list, or by javascript. The trick is in the third parameter of the DropDownList extension method:

@Html.DropDownList("VBPais", ViewBag.VBPais as SelectList, "-- SELECCIONE --", new { @class = "form-control" })

With the note that makes you out there, where they say that the option would have an empty value and that ends up helping you for example in validations. You would find a select-option like this:

<select class="form-control" id="VBPais" name="VBPais">
  <option value="">-- SELECCIONE --</option>
  <option value="1">VALOR1</option>
  <option value="2">VALOR2</option>
  <option value="3">VALOR3</option>
</select>
    
answered by 24.01.2018 в 19:35