How to load a dropdown with a selected value

6

I have a method to perform change on some data. Among these data, I have a dropdownlist that contains the periods of the courses. When I select to change, I need the dropdown to come with the option checked, as it is in the database.

I need it selected "Night", as it is in the database:

Ineeditselected"Night", as it is in the database

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

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

3 answers

10

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 way is 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" })
    
08.06.2015 / 19:09
3

Make a FOR by searching the list of periods and makes a SELECT by returning the values of the course out of FOR .

From there inside the FOR you make a IF checking if the field being listed is the same as the course field. If it is, you determine SELECTED in the OPTION field.

<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 do not program in C #, but I understand the logic of the routine.

    
08.06.2015 / 19:01
0

Dude, I do not know how it is in your cxontroller, but I would try it here in the controller

Controller:

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

And here in 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>
    
08.06.2015 / 19:13