简体   繁体   中英

Populating a dropdown list using a for loop in razor

I know it is not the best practice to do this, but I am curious on how you would populate a dropdownlist using a for loop in razor.

I am trying to do it this way

@{
      int year = DateTime.Now.Year;

      @Html.DropDownListFor(model => model.ResolutionYear, new List<SelectListItem>
      {
          for (var i = 0; i < 10; i++)
          {
              if (year - i == year)
              {
                  new SelectListItem() { Text = (year - i).ToString(), Value = (year - i).ToString(), Selected = true };
              }
              else
              {
                  new SelectListItem() { Text = (year - i).ToString(), Value = (year - i).ToString() };
              }
          }
        })
}

It doesn't seem to like the way I am doing it as it keeps shouting at me } expected I have all all the closing brackets for each open bracket. Perhaps I am populating my DropDownList wrong? Is it even possible to populate this way or should I just do it in the controller?

Don't do it. Keep your Views as benign as possible. Use your View Model and Controller, that's what they're for. But for curiosity's sake, here's one way:

@{ var year = DateTime.Now.Year; }
<select>
@for (var i = year; (i > year - 10); i--)
{
    if (i == (year - 3))
    {
        <option value="@i" selected>@i</option>
    }
    else
    {
        <option value="@i">@i</option>
    }
}
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM