Apply selected on a select with Razor

0

I have the following code in a file with cshtml extension:

@Html.DropDownList("TipoIdentificacionId", null, htmlAttributes: new { @class = "form-control" })

With which I load in a select a list that comes from the database, this does it well, but I would like to know if it is possible with the same razor syntax to apply the selected attribute of html to a certain option.

    
asked by Alberto Atencio 16.05.2018 в 23:02
source

2 answers

0

What you could do, would be to assign the property Selected to the item that you intend from the same Controller

For example;

Driver

    public ActionResult Index()
    {
        //Creo una lista de ejemplo
        List<SelectListItem> opciones = new List<SelectListItem>()
        {
            new SelectListItem{ Text="Texto 1", Value="Value 1" },
            new SelectListItem{ Text="Texto 2", Value="Value 2" },
            new SelectListItem{ Text="Texto 3", Value="Value 3" },
            new SelectListItem{ Text="Texto 4", Value="Value 4" }
        };

        //Recorro la lista (que en tu caso vendría creada de otro lugar, asumo
        foreach(var opcion in opciones)
        {
            //Evalúo la condición que me llevaría a hacer que esa opción este seleccionada
            if (opcion.Text.Contains("4"))
            {
                //La selecciono
                opcion.Selected = true;
            }
        }
        //Por último la asigno a un ViewBag y retorno la vista
        ViewBag.opciones = opciones;

        return View();
    }

Vista

@Html.DropDownList("prueba",(List<SelectListItem>)ViewBag.opciones,null,null)

And in case you use the strongly typed method

@Html.DropDownListFor(x => x.tu_variable, (List<SelectListItem>)ViewBag.opciones,null,null)

Greetings

    
answered by 17.05.2018 в 00:00
0

I would eliminate the ViewBags of my jobs and use ViewModel simply because the development becomes much more scalable and easy to maintain, so I would start creating a ViewModel with the properties you need

public class SelectViewModel
{
   public int SelectedOption { get; set; }
   public IEnumerable<SelectListItem> Lista { get; set; }
} 

And we continue with the obtaining of the data and the selection of the default option that you want to show:

public ActionResult MiAccion()
{
   List<SelectListItem>data = new List<SelectListItem>
   {
      new SelectListItem{ Text="Chile", Value = "1" },
      new SelectListItem{ Text="Argentina", Value = "2" },
      new SelectListItem{ Text="España", Value = "3" },
      new SelectListItem{ Text="Brasil", Value = "4" },
      new SelectListItem{ Text="Paraguay", Value = "5" },
      new SelectListItem{ Text="Colombia", Value = "6" },
      new SelectListItem{ Text="Ecuador", Value = "7" },
      new SelectListItem{ Text="Perú", Value = "8" },
      new SelectListItem{ Text="Venezuela", Value = "9" },
      new SelectListItem{ Text="Bolivia", Value = "10" }
   };

   string optionSelected = string.Empty;
   foreach (SelectListItem item in data)
   {
      if (item.Value == "6")
         optionSelected = item.Value;
   }

   SelectViewModel model = new SelectViewModel
   {
      SelectedOption = int.Parse(optionSelected),
      Lista = data.Select(x => new SelectListItem
      {
         Value = x.Value,
         Text = x.Text
      })
   };

   return View(model);
}

And finally we link the model to the view with the data:

@model SelectViewModel
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

@Html.DropDownListFor( x => x.SelectedOption, Model.Lista)

I've attached the result to you in .NET Fiddle link

    
answered by 17.05.2018 в 00:10