How to keep the selected value in a select after the post back

1

Hi how can I pantener the selected value of a select after the postback?  this is the code that I have in sight:

<select id="LocalidadId" name="LocalidadId" class="btn btn-secondary btn-block" asp-items="ViewBag.LocalidadId">
    <option>Selecciona una localidad</option>
</select>

This is the code in the controller:

ViewData["LocalidadId"] = new SelectList(await queryLocalidades.ToListAsync(), "LocalidadId", "Localidad1", null, "Municipio1");

After submitting; again the default value is set in the select: "Select a location", but my wish is that the selected location be maintained in the select after submitting to be able to perform filtering and sorting operations in that specific location. I hope you have explained me well and that you can guide me.

    
asked by Daniel 23.09.2017 в 23:03
source

1 answer

1

Try to get the selected value of the control and in SelectList find which item has the value and assign the property% co_from% to true:

var selectList = new SelectList(await queryLocalidades.ToListAsync(), "LocalidadId", "Localidad1", null, "Municipio1");


// obtienes el valor seleccionado cuando se hizo el postback
var valorSeleccionado = obtenerValorSeleccionadoSelectList();
foreach(var item in selectList)
{
  if(item.Value == valorSeleccionado)
  {
     item.Selected = true;
  }
}

// signas el select list al control
ViewData["LocalidadId"] = selectList;
    
answered by 23.09.2017 в 23:32