How to load a dropdown with a selected value

Asked

Viewed 4,902 times

6

I have a method to make changes in some data. Among these data, I have a dropdownlist which contains course periods. When I select to change, I need the dropdown comes with the option checked, as it is in the database.

I need him to come selected "Night" as it is in the bank:

Preciso que ele venha selecionado "Noite", conforme está no banco

Here is the select of dropdown. The @ViewBag.Periodos I pass through the method Alterar in the Controller:

<select name="selPeriodo" class="form-control">
      @{
          foreach (var item in @ViewBag.Periodos)
          {
             <option value="@item.Id">@item.Nome</option>
          }
       }                
</select>

3 answers

12


The most succinct way to write this is like this:

<select name="selPeriodo" class="form-control">
      @foreach (var item in @ViewBag.Periodos)
      {
         <option value="@item.Id" @(Model.PeriodoId == item.Id ? "selected" : "")>@item.Nome</option>
      }
</select>

The recommended form is like this:

@Html.DropDownListFor(model => model.PeriodoId, ((IEnumerable<Periodo>)ViewBag.Periodos).Select(periodo => new SelectListItem {
    Text = periodo.Nome,
    Value = periodo.Id,
    Selected = (Model != null) && (Model.PeriodoId == periodo.Id)
}), "Escolha um Período", new { @class = "form-control" })
  • 2

    I believe you have no better answer

  • @Maiconcarraro I was going to comment on yours, but you excluded :(

  • Calm down, your answer is more complete so I have no reason to keep mine.

  • 1

    Manda a lot. It worked perfectly. Thanks @Ciganomorrisonmendez for the reply and the others too!

  • Do I always have to go through using a Viewbag or is there some other way? I’m trying to implement something similar only using a Viewmodel, but I’m not getting it.

  • 1

    You can put the Dropdown values inside the Viewmodel, although this takes a little more work. Ask another question that I present to you the detailed approach.

  • @I asked a more detailed question about my problem. Follow the link http://answall.com/questions/184758/pega-um-item-selected-no-dropdownlistfor-usando-uma-viewmodel-asp-net-mvc

Show 2 more comments

3

Makes a FOR searching the list of periods and makes a SELECT returning the course values outside the FOR.

From there on in the FOR you make a IF checking whether the field being listed is equal to the course field. If it is, you determine the SELECTED in the field OPTION.

<select name="selPeriodo" class="form-control">
      @{
          foreach (var item in @ViewBag.Periodos)
          {
             if (@item.id == @periodo) // Campo do FOR = Campo Período do Curso
             {
                 <option value="@item.Id" selected>@item.Nome</option>
             }
             else
             {
                 <option value="@item.Id>@item.Nome</option>
             }
          }
       }                
</select>

Probably my C# code is wrong because I don’t program in C#, but I understand the logic of the routine.

0

Dude, I don’t know what’s going on with your cxontroller, but I’d try that here at the controller

Controller:

ViewBag.PediodoId = new SelectList(db.Periodos, "Id", "Nome", curso.PeriodoId);

and this here in the View:

<div class="form-group">
        @Html.LabelFor(model => model.PeriodoId, "PeriodosId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("PeriodoId", null, htmlAttributes: new { @class = "form-control" })


@Html.ValidationMessageFor(model => model.PeriodoId, "", new { @class = "text-danger" })
        </div>
    </div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.