Search code examples
c#asp.net-corerazordropdownlistfor

DropDownListFor value default


I have the following code, and I need it to have a default value. `

@Html.DropDownListFor(m =\> m.Articulo.CategoriaId, Model.ListaCategorias,
"Seleccione una categoría", new { @class = "form-control" })

` is simple no?

My intention is to achieve a default value, but I have this dropdown list and I don't know much about C#, if I can at least achieve a default value, I'll be fine.


Solution

  • You can try to use @foreach to check which option you want to be the selected one:

    <select asp-for="Articulo.CategoriaId" class="form-control">
        <option value="">Seleccione una categoría</option>
        @foreach (var item in l)
        {
            if (item.xxx=="xxx")
            {
                <option selected [email protected]>@item.xxx</option>
            }
            else
            {
                <option [email protected]>@item.xxx</option>
            }
    
        }
    </select>