C# Html.DropDownList - 如何添加额外的 <option> 到列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9615502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html.DropDownList - How to add extra <option> to list
提问by Chris
I am using Html.DropDownListto create an options list like so
我正在使用Html.DropDownList这样创建一个选项列表
Html.DropDownList("LogType", new SelectList(Model.LogTypeList, "ID", "Name", Model.SelectedLogType),"-- ALL --");
As you can see I pass in a list but also pass in an extra argument to add an additional option: "-- All --". The result is as follows:
正如你可以看到我传递一个名单,但也传递一个额外的参数添加额外的选项:"-- All --"。结果如下:
<select name="LogType" id="LogType">
<option value="">-- ALL -- </option>
<option value="1">Debug</option>
<option value="2" selected="selected">Error</option>
</select>
How do I give -- All --an value of 0 without having to manually construct the drop down list myself?
如何在-- All --不必自己手动构建下拉列表的情况下给出0 值?
采纳答案by Mohammed Swillam
I'm not sure but, why don't you construct the list just before your @html.DropDownList
我不确定但是,你为什么不在你之前构建列表 @html.DropDownList
var myList = new SelectList(Model.LogTypeList, "ID", "Name", Model.SelectedLogType);
and then append your desired item to it.
然后将您想要的项目附加到它。
var myList.add(new selectItem("-- ALL --",0));
and finally pass it to your syntax and see what this will result
最后将它传递给你的语法,看看会产生什么结果
Html.DropDownList("LogType",myList);
sorry, this is a quick answer using my iPhone, not sure if it will fix your problem, but I tried to help as much as I could.
抱歉,这是使用我的 iPhone的快速回答,不确定它是否能解决您的问题,但我已尽力提供帮助。
回答by Simon Wang
I tried to do this before and end with using jQuery:
我之前尝试这样做并以使用 jQuery 结束:
$("#LogType").append($("<option />").val("0").html("-- All --"));
回答by PoorbandTony
Just for a different approach, I was amazed at how many answers on forums there were for this same question, all of which seemed overly complex for what can be achieved easily in WebForms with AppendDataItems (granted, it iswebforms!).
只是对于不同的方法,我很惊讶论坛上有多少针对同一问题的答案,所有这些对于使用 AppendDataItems 在 WebForms 中可以轻松实现的内容来说似乎过于复杂(当然,它是Webforms !)。
This worked well for me a few moments ago, keeping everything inline and keeping the view and model concerns separate:
几分钟前,这对我来说效果很好,将所有内容保持内联并将视图和模型关注点分开:
@Html.DropDownListFor(model => model.Operators,
new SelectList(new[] {
new {id=-1, name="Please select an operator"}}
.Union(Model.Operators
.Select( o=> new { id=o.Id, name=o.Name})
), "id", "name"))
Which renders out as :
呈现为:
<select id="Operators" name="Operators">
<option value="-1">Please select an operator</option>
<option value="1">Tony Bolton</option>
<option value="2">Joe Bloggs</option>
</select>
Haven't checked performance etc though, but felt it was worth sharing.
虽然没有检查性能等,但觉得值得分享。

