MVC4 当列表包含值为 0 的 SelecListItem 时,在 DropDownList 中设置默认 SelectListItem

MVC4 Set default SelectListItem in DropDownList when the list contains a SelecListItem with value 0

我正在尝试将我认为的默认 SelectListItem 设置为 ---Select---,值为 null。这个应该很简单。

我知道这可以在视图中使用这个重载示例来完成。

@Html.DropDownListFor(m=> m.SelectedId, M.List, "---Select---", null)

但是,这是我遇到问题的地方,我试图设置默认值的这个列表有一个值为 0 的 SelectListItem。

 @Html.DropDownListFor(model => Model.Vat, new List<SelectListItem>
                        {
                        new SelectListItem{Text = "Normal 20%", Value = "20"},
                        new SelectListItem{Text = "Reduced 5%",Value = "5"},
                        new SelectListItem{Text = "Exempt", Value = "0",} //This is the cause of the problem
                        }, "---Select---", null)

现在发生的事情是当我的视图加载时,---Select--- 选项位于列表的顶部,值为 null,正如预期的那样,但是默认选择的列表项是 "Exempt",据我所知,这是因为 MVC 将默认下拉列表项设置为值为 0 的任何选项。

我已经尝试了许多不同的解决方法,例如添加

new SelectListItem{Text = "Test", Value = null, Selected = true }

但是当页面加载时仍然没有选择这个,我试过的其他方法都没有用。

我无法避免使用值为 0 的豁免选项,因为我的申请需要此信息。

我已经搜索并搜索了这个问题的答案,但没有找到任何帮助,如果有人能指出我正确的方向以及如何处理这个问题,我将不胜感激。

使 属性 可为空:

public int? Vat { get; set;}

原因是 int 的默认值为 0,因此当您的模型在 post 期间绑定时,您的 属性 的值将设置为0 即使所选值为空,因为 int 不可为空但 int? 为。