如何将 List<string> 传递给下拉列表?

How to pass List<string> to dropdown?

我有一个列表如下:

List<string>WeekEnding={'10/07/2018','11/11/2018','01/21/2018'};

我想将其传递给名称='10/07/2018' 值='10/07/2018'的下拉列表

我的下拉菜单是

  @Html.DropDownList("WeekEnding", null, new { Id = "WeekEnding", style = "width:50px;", @class = "form-control js-select", @size = "2" , required = "required" })  

你可以这样使用

@model List<string>
@Html.DropDownList(
    "WeekEnding", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),//you have to pass data as model. If you use another way you must change this line. 
        "Value",
        "Text"
    ),
    new { Id = "WeekEnding", style = "width:50px;", @class = "form-control js-select", @size = "2" , required = "required" }
)

我通常使用 view models 来填充我的下拉列表,即使它具有日期等基本值(如您的代码中所示)。按照你想要的方式工作,我会像下面那样做。

假设您正在使用 Index action methodIndex view..

索引操作方法

public ActionResult Index()
{
    List<string> WeekEnding = new List<string>() { "10/07/2018", "11/11/2018", "01/21/2018" };

    return View(WeekEnding);
}

索引视图

@model List<string>

@Html.DropDownList(
    "WeekEnding",
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    ),
    "-- Select --",
    new { @style = "width: 50px", @class = "form-control js-select", @size = "2", @required = "required" }
)

在页面生成后查看 HTML 源时,将如下所示:

<select class="form-control js-select" id="WeekEnding" name="WeekEnding" required="required" size="2" style="width: 50px">
    <option value="">-- Select --</option>
    <option value="10/07/2018">10/07/2018</option>
    <option value="11/11/2018">11/11/2018</option>
    <option value="01/21/2018">01/21/2018</option>
</select>

希望对您有所帮助。