5

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>
4

2 回答 2

10

DropDownFor 参数的文档中optionLabel您传递“None”)被描述为:

默认空项目的文本。

所以这被设计为始终是一个空项目。您需要在选择列表中添加一个附加项目才能获得 0 值。

我使用了以下扩展方法来完成此操作(抱歉未经测试,可能存在小错误):

public IEnumerable<SelectListItem> InsertEmptyFirst(this IEnumerable<SelectListItem> list, string emptyText = "", string emptyValue = "")
{
    return new [] { new SelectListItem { Text = emptyText, Value = emptyValue } }.Concat(list);
}

你会像这样使用它:

@Html.DropDownListFor(model => model.cardReward.ID, new SelectList(ViewBag.cardReward, "Id","Name").InsertEmptyFirst("None", "0"))
于 2013-08-09T19:05:26.947 回答
1

插入一个新的空字符串,这里是一个例子。

@Html.DropDownListFor(x => x.ProjectID, Model.Projects, string.Empty)
于 2015-10-22T13:50:51.137 回答