Search code examples
c#asp.net-mvcasp.net-mvc-5razor-2dropdownlistfor

How to select values in a multiple DropDownList using DropdownListFor in MVC 5


I have this model:

public class CampoTipoDocumentoViewModel
{
    public int TipoDocumentoId { get; set; }

    public string[] CamposId { get; set; }

    private List<MiddleTier.Models.ICampo> _todosCampos;
    public IEnumerable<SelectListItem> TodosCampos
    {
        get
        {
            foreach (var campo in _todosCampos)
                yield return new SelectListItem { Text = campo.Nombre, Value = campo.Id.ToString() };
        }
    }  

    public void SetFields(List<MiddleTier.Models.ICampo> campos)
    {
        _todosCampos = campos;
    }
}

In controller, CamposId property is assigned with elements which has to be selected in the view.

Controller also calls SetFields method populating _todosCampos to the whole list of records in the system.

The idea is to create a View with a SELECT that has initially some records selected.

This is my view:

@Html.DropDownListFor(m => m.CamposId, Model.TodosCampos, new { @class = "form-control", multiple = "multiple", width = "100%" })

The fact is that the HTML SELECT element is created with the list, but no option is selected.

For example, if _todosCampos contains:

Text = "One", Value = "1"
Text = "Two", Value = "2"
Text = "Three", Value = "3"
Text = "Four", Value = "4"

and CamposId contains:

Array of "2", "4"

I need the view to create a SELECT with those 4 options, and option 2 and 4 to be initially selected.

How can I achieve this?

Thanks Jaime


Solution

  • In order to use <select> element with multiple="multiple" attribute, you need to declare List<string> property:

    public List<string> CamposId { get; set; }
    

    And then use ListBoxFor helper instead of DropDownListFor:

    @Html.ListBoxFor(m => m.CamposId, Model.TodosCampos, new { @class = "form-control", multiple = "multiple", width = "100%" })
    

    If you want to set some option values are selected by default, then set Selected property into SelectListItem:

    public IEnumerable<SelectListItem> TodosCampos
    {
        get
        {
            foreach (var campo in _todosCampos)
            {
                // assumed you have 'campo.IsDefault' which is boolean property 
                yield return new SelectListItem 
                { 
                    Text = campo.Nombre, 
                    Value = campo.Id.ToString(), 
                    Selected = campo.IsDefault // set default selected values
                };
            }
        }
    }  
    

    Note: Usually ID property contain integer values, you can try for List<int> CamposId depending on actual ID data type in database.