在我的MVC控制器中,我可以向我的HTML.DropDownList添加一个值吗?
问题描述:
在我看来,我有一个HTML DropDownList,在我的控制器中使用List<string>
填充。在我的MVC控制器中,我可以向我的HTML.DropDownList添加一个值吗?
<%= Html.DropDownList("ReportedIssue", (IEnumerable<SelectListItem>)ViewData["ReportedIssue"]) %>
List<string> reportedIssue = new List<string>();
reportedIssue.Add("All");
reportedIssue.Add(...);
ViewData["ReportedIssue"] = new SelectList(reportedIssue);
在我看来,其结果是:
<select name="ReportedIssue" id="ReportedIssue">
<option>All</option>
<option>...</option>
</select>
有没有办法做到这一点,还包括在每一个<option>
标签像这样的价值呢?
<select name="ReportedIssue" id="ReportedIssue">
<option value="0">All</option>
<option value="1">...</option>
</select>
谢谢
亚伦
答
你能刚刚超过列表并输出其在视图中循环?
(也传递Id以及文本我会创建一个字典,并将其添加到您的视图模型/ ViewData)。
在视图:
<select name="ReportedIssue" id="ReportedIssue">
<option value="0">All</option>
<% foreach(int key in myDictionary.Keys) { %>
<option value="<%= key %>"><%= myDictionary[key] %></option>
<% } %>
</select>
答
您可以只需稍作修改代码做到这一点。您需要决定如何定义您的价值物品。现在我只是把一个评论,你可以做到这一点:
ViewData["ReportedIssue"] = new SelectList(reportedIssue
.Select(r => new SelectListItem
{
Text = r,
Value = someIdValue // define this however you want
}));
所以只是这一个取代你的代码并运行someIdValue
占位符。
我不会使用ViewData ...我会使用ViewModel。 – Martin 2010-09-02 01:55:03
@Martin我同意这一点,但这不是'必要的',只是一个好习惯:) – Kelsey 2010-09-02 03:43:38