【发布时间】:2017-08-25 11:49:01
【问题描述】:
我想在没有任何模型的情况下使用@Html.DropDownList,就像我们在普通html中使用select一样。
请恢复,谢谢!
【问题讨论】:
-
为什么不直接使用普通的html?
-
因为我想将来自控制器的值绑定为其默认值。 @DaveBecker
标签: c# html asp.net-mvc
我想在没有任何模型的情况下使用@Html.DropDownList,就像我们在普通html中使用select一样。
请恢复,谢谢!
【问题讨论】:
标签: c# html asp.net-mvc
它很简单,你可以理解我们下面的例子。
@Html.DropDownList("selectedState", new List<SelectListItem>
{
new SelectListItem {Text = "Not verified", Value = "1"},
new SelectListItem {Text = "Verified", Value = "2"},
new SelectListItem {Text = "Migrated", Value = "3"}
new SelectListItem {Text = "Completed", Value = "4"}
}, "All states", new { @onchange = "form.submit();", @class = "form-control" })
【讨论】:
你可以在没有模型的情况下使用@Html.Dropdownlist 例如在控制器中设置下拉列表的值,
var dates = new List<SelectListItem>{
new SelectListItem {Selected = false, Text = "Show offers for all dates", Value = ""},
new SelectListItem {Selected = false, Text = "Show offers for today", Value = today.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this week", Value = endOfThisWeek.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for this month", Value = endOfThisMonth.ToShortDateString()},
new SelectListItem {Selected = false, Text = "Show offers for further out", Value = all.ToShortDateString()},};
ViewBag.Dropdowndata = dates;
您可以从 View 访问 Viewbag 的值并将其设置为下拉列表,如
@using (Html.BeginForm())
{
<label>
Select Dates</label>
@Html.DropDownList("Dates", (IEnumerable<SelectListItem>)ViewBag.Dropdowndata, "---Select---", new { id = "dateList" ,@class = "form-control" });
}
【讨论】: