Pablo Tobar
Pablo Tobar

Reputation: 634

shows a specific value in MVC DropDownList that matchs a viewbag value

I do have a Html.DropDownListFor in a MVC C# App whre the user can selects specific values(years: 2017, 2018, 2019, 2020) as shows below

            <div class="col-md-3">
                @Html.LabelFor(model => model.correlativo2, htmlAttributes: new { @class = "control-label" })
                <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">Seleccione</span>
                    @Html.DropDownListFor(model => model.correlativo2, new List<SelectListItem> { new SelectListItem { Text = "2017", Value = "2017" }, new SelectListItem { Text = "2018", Value = "2018" }, new SelectListItem { Text = "2019", Value = "2019" }, new SelectListItem { Text = "2020", Value = "2020" }, new SelectListItem { Text = "2021", Value = "2021" } }, "", new { @class = "form-control", @id = "idEjercicio", @title = "especifique ejercicio de licitación", @Value = ViewBag.ejercicio })
                </div>
                @Html.ValidationMessageFor(model => model.correlativo2, "", new { @class = "text-danger" })
            </div>

since the values are constant(years) and wont change(neither depends on any other value) I dont query the database to specify the values of the dropdownlist but it can happens that the @Value = ViewBag.ejercicio has a specific value (for instance: 2017, 2018, 2019, 2020) so I want the dropdownlist to show the year that match the value but it shows nothing even if the Viewbag has a value.

Ths is the ViewBag: ViewBag.ejercicio = Convert.ToString(datos.correlativo2); could you please help me

Upvotes: 0

Views: 250

Answers (1)

Andrii Litvinov
Andrii Litvinov

Reputation: 13182

You can try setting Selected property and using DropDownList instead:

<div class="col-md-3">
    @Html.LabelFor(model => model.correlativo2, htmlAttributes: new { @class = "control-label" })
    <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">Seleccione</span>
        @{
            var years = new List<SelectListItem> { new SelectListItem { Text = "2017", Value = "2017" }, new SelectListItem { Text = "2018", Value = "2018" }, new SelectListItem { Text = "2019", Value = "2019" }, new SelectListItem { Text = "2020", Value = "2020" }, new SelectListItem { Text = "2021", Value = "2021" } };
            foreach (var year in years) 
            {
                year.Selected = year.Value == ViewBag.ejercicio;
            }
        }

        @Html.DropDownList("correlativo2", years, "", new { @class = "form-control", @id = "idEjercicio", @title = "especifique ejercicio de licitación" })
    </div>
    @Html.ValidationMessageFor(model => model.correlativo2, "", new { @class = "text-danger" })
</div>

But it is indeed better to set value of the model property as @AndrewReyes suggested. Then Razor will automatically set selected value for you.

Upvotes: 1

Related Questions