2012-10-05 74 views
2

在我的MVC窗体上,我需要将下拉框绑定到ViewModel上的枚举。我发现这样做的最佳方式是hereDropDownListFor枚举不会绑定回模型

它似乎最初工作,但现在我已经添加验证到我的表单,我发现它不绑定回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; } 

的问题是,我不能提交表单;即使在从我的下拉菜单中选择响应后,也会显示“范围”属性的“验证”错误消息,并且客户端验证会阻止表单提交。

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

我该如何解决这个问题?

+0

当你知道你绑定的范围并且已经有'Required'时,为什么你需要'Range'属性? – asawyer

+0

Required属性似乎不是自己的工作 - 响应字段默认值为0.其实我可以只需要出去,它似乎没有任何效果 – Slider345

回答

5

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

@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") 

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

+0

感谢这工作!虽然原来需要转换才能从Enum.GetValues返回的System.Array转换为ToDictionary所需的IEnumerable。我建议编辑这个效果。 – Slider345