如何通过手动赋值来使用@Html.DropDownList? [复制]
Posted
技术标签:
【中文标题】如何通过手动赋值来使用@Html.DropDownList? [复制]【英文标题】:How to use @Html.DropDownList by giving values manually? [duplicate] 【发布时间】:2017-08-25 11:49:01 【问题描述】:我想在没有任何模型的情况下使用@html.DropDownList
,就像我们在普通html中使用select一样。
请恢复,谢谢!
【问题讨论】:
为什么不直接使用普通的html? 因为我想将来自控制器的值绑定为其默认值。 @DaveBecker 【参考方案1】:它很简单,你可以理解我们下面的例子。
@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" )
【讨论】:
【参考方案2】:你可以在没有模型的情况下使用@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" );
【讨论】:
以上是关于如何通过手动赋值来使用@Html.DropDownList? [复制]的主要内容,如果未能解决你的问题,请参考以下文章