简体   繁体   English

在剃刀中使用for循环填充下拉列表

[英]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. 我知道这不是最佳做法,但是我很好奇您如何使用剃刀中的for循环填充dropdownlist

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. 似乎不喜欢我的操作方式,因为它一直在高喊我} expected我每个开放式括号都有所有的封闭式括号。 Perhaps I am populating my DropDownList wrong? 也许我在DropDownList我的DropDownList错误? 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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