我有一个列表如下:
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 method
和Index 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>
我希望这有帮助。