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

时间:2019-02-27 05:18:48

标签: c# .net asp.net-mvc dropdown viewbag

我的列表如下:

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

我想将其传递给name = '10 / 07/2018'value = '10 / 07/2018'的下拉列表

我的下拉列表是

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

2 个答案:

答案 0 :(得分:1)

您可以这样使用

@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" }
)

答案 1 :(得分:1)

我通常使用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>

我希望这会有所帮助。