Alsan
Alsan

Reputation: 325

Set Dropdownlist default value dynamically

I have this dropdownlist defined in a model

tipoUsuario = new List<SelectListItem>();            
tipoUsuario.Add(new SelectListItem { Text = "Sin tipo", Value = "4" });                
tipoUsuario.Add(new SelectListItem { Text = "1 - Super usuario", Value = "1"});                
tipoUsuario.Add(new SelectListItem { Text = "2 - Administrador", Value = "2" });
tipoUsuario.Add(new SelectListItem { Text = "3 - Usuario", Value = "3" });                

public List<SelectListItem> tipoUsuario { get; set; }

The view shows a list of elements, each of the elements has a dropdownlist, each of which must have a different default selected value based on a value from the controller. Now i am showing "Administrator" but i want the default value...

if (@item.type == "2")
{                      
    @Html.DropDownListFor(x => item.type, item.tipoUsuario, "Administrator")                
}

I have being trying lot of options but i don't know how to do it, help me please

Thaning you in advance!

Upvotes: 1

Views: 4644

Answers (1)

Mister Epic
Mister Epic

Reputation: 16723

You need to set the "Selected" property to true on your SelectListItem. You could create a population method like:

public IEnumerable<SelectListItem> PopulateTipoUsuario(string default){
    var tipo = from t in source
                    select new SelectListItem
                    {
                        Text = t.Text,
                        Value = t.Value,
                        Selected = t.Text == default
                    };
        return tipo;
}

The source variable would be your original collection of SelectListItems:

var source = new List<SelectListItem>();            
tipoUsuario.Add(new SelectListItem { Text = "Sin tipo", Value = "4" });                
tipoUsuario.Add(new SelectListItem { Text = "1 - Super usuario", Value = "1"});                 
tipoUsuario.Add(new SelectListItem { Text = "2 - Administrador", Value = "2" });
tipoUsuario.Add(new SelectListItem { Text = "3 - Usuario", Value = "3" });   

Upvotes: 1

Related Questions