MVC 4:如何使DropDownListFor返回0作为optionLabel价值? [英] MVC 4: How to make DropDownListFor return 0 as optionLabel value?
问题描述
我有多个DropDownListFors一个创建视图。每次创建新的对象只有DropDownListFors 1应该有一个值的时候,我要当左侧所选optionLabel其他人返回0作为结果。
我如何分配0作为一个DropDownListFor的optionLabel价值?
编辑:
这是在我看来,我的DropDownListFor code的例子:
@ Html.DropDownListFor(型号=> model.cardReward.ID,新的SelectList(ViewBag.cardReward,ID,姓名),无)
当我渲染页面就在这样的顶部创建了无名单:
<选项值>无< /选项>
我希望它是这样的:
<期权价值=0>无< /选项>
在为DropDownFor文档的 optionLabel
参数(如果你传递无)被描述为:
该文本默认为空项。
块引用>所以这样的设计永远是一个空的项目。您将需要一个额外的项目添加到您的选择列表,以获得一个0值。
我用下面的扩展方法来做到这一点(对不起未经测试,可能会有小错误):
公开的IEnumerable< SelectListItem> InsertEmptyFirst(这IEnumerable的< SelectListItem>列表中,字符串emptyText =,字符串emptyValue =)
{
返回新的[] {新SelectListItem的{text = emptyText,值= emptyValue}} .Concat(名单);
}您会使用这样的:
@ Html.DropDownListFor(型号=方式> model.cardReward.ID,新的SelectList(ViewBag.cardReward,ID,姓名)InsertEmptyFirst(无, 0))
I have a create view with multiple DropDownListFors. Each time a new object is created only 1 of the DropDownListFors should have a value, I want the others to return 0 as the result when the optionLabel is left selected.
How do I assign 0 as the value for a DropDownListFor's optionLabel?
EDIT: Here is an example of my DropDownListFor code in my view:
@Html.DropDownListFor(model => model.cardReward.ID, new SelectList(ViewBag.cardReward, "Id","Name"), "None")
When I render the page it creates the list with None at the top like this:
<option value>None</option>
I want it to be like this:
<option value="0">None</option>
解决方案In the documentation for DropDownFor the
optionLabel
parameter (where you're passing "None") is described as:The text for a default empty item.
So this is designed to always be an empty item. You will need to add an additional item into your select list in order to get a 0 value.
I have used the following extension method to accomplish this (sorry untested, there may be minor errors):
public IEnumerable<SelectListItem> InsertEmptyFirst(this IEnumerable<SelectListItem> list, string emptyText = "", string emptyValue = "") { return new [] { new SelectListItem { Text = emptyText, Value = emptyValue } }.Concat(list); }
You would use it like this:
@Html.DropDownListFor(model => model.cardReward.ID, new SelectList(ViewBag.cardReward, "Id","Name").InsertEmptyFirst("None", "0"))
这篇关于MVC 4:如何使DropDownListFor返回0作为optionLabel价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!