Sli*_*345 2 validation asp.net-mvc asp.net-mvc-3
在我的MVC表单上,我需要将一个下拉框绑定到我的ViewModel上的枚举.我发现这样做的最好方法在这里描述.
它似乎首先工作,但现在我已经在我的表单中添加了验证,我发现它没有绑定回ViewModel.
这是我的剃刀代码:
<div class="editor-field">
@Html.DropDownListFor(model => model.response,
new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType))),
"Please Select")
</div>
Run Code Online (Sandbox Code Playgroud)
这是我对该领域的视图模型定义:
[DisplayName("Response")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a response before submitting this form.")]
public ResponseType response { get; set; }
Run Code Online (Sandbox Code Playgroud)
问题是我无法提交表格; 即使从我的下拉列表中选择响应后,也会显示Range属性的Validation错误消息,并且客户端验证会阻止表单提交.
我相信这是因为下拉列表的SelectList只包含枚举的字符串名称,而不包含基础整数值.
我怎么解决这个问题?
创建字典,其中Key将是枚举和字符串的整数表示 - 枚举的名称.
@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")
Run Code Online (Sandbox Code Playgroud)
对不起可能的错误,我还没试过.
| 归档时间: |
|
| 查看次数: |
1485 次 |
| 最近记录: |