【问题标题】:DropDownListFor enum doesn't bind back to the modelDropDownListFor 枚举不绑定回模型
【发布时间】:2012-10-05 17:55:40
【问题描述】:

在我的 MVC 表单上,我需要将一个下拉框绑定到我的 ViewModel 上的一个枚举。我发现这样做的最佳方法是 here

一开始它似乎可以工作,但现在我已经向我的表单添加了验证,我发现它并没有绑定回 ViewModel。

这是我的剃须刀代码:

<div class="editor-field">
    @Html.DropDownListFor(model => model.response, 
                          new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType))),
                          "Please Select")
</div>

这是我对该字段的视图模型定义:

[DisplayName("Response")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a response before submitting this form.")]
public ResponseType response { get; set; }

问题是我无法提交表单;即使从我的下拉列表中选择了响应,也会显示 Range 属性的验证错误消息,并且客户端验证会阻止表单提交。

我相信这是因为下拉列表的 SelectList 只包含枚举的字符串名称,而不是基础整数值。

我该如何解决这个问题?

【问题讨论】:

  • 当您知道要绑定的范围并且已经拥有Required 时,为什么还需要Range 属性?
  • Required 属性好像不能单独工作——响应字段默认值为0。其实我可以把Required 去掉,好像没有效果

标签: asp.net-mvc asp.net-mvc-3 validation


【解决方案1】:

创建字典,其中键将是枚举的整数表示形式和字符串 - 枚举的名称。

@Html.DropDownListFor(model => model.response, 
                      new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType)).OfType<Vouchers.Models.VoucherResponseType>().ToDictionary(x => Convert.ToInt32(x), y => y.ToString()), "Key", "Value"), "Please Select")

对不起,可能的错误,我没有尝试过。

【讨论】:

  • 感谢这工作!尽管为了从 Enum.GetValues 返回的 System.Array 到 ToDictionary 所需的 IEnumerable,需要进行强制转换。我建议对此进行修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
相关资源
最近更新 更多