2

我有一个具有如下属性的模型:

[Required]
public int SingleSelect { get; set; }

比我在控制器中设置一个 SelectList 并将它传递给 viewbag

public ActionResult Index()
    {
        ViewBag.SingleSelectList = new SelectList(new[]
                                      {
                                          new {ID="0",Name="-- Select --"},
                                          new {ID="1",Name="Select 1"},
                                          new{ID="2",Name="Select 2"},
                                          new{ID="3",Name="Select 3"},
                                      },
                        "ID", "Name", 0);


        return View();
    }

然后在 View() 上,我使用以下内容呈现一个不错的下拉框:

@Html.LabelFor(obj => obj.SingleSelect, new { @class = "control-label"})
@Html.DropDownListFor(obj => obj.SingleSelect, ViewBag.SingleSelectList as SelectList)
@Html.ValidationMessageFor(obj => obj.SingleSelect)

<button class="btn btn-primary" type="submit">Validate!</button>

如果用户没有在表单提交上做出选择(仍然在选项“--选择--”上),如何让验证工作显示错误?

4

1 回答 1

2

您可以尝试两种方法,首先

[Required, Range(1, Int32.MaxValue)]
public int SingleSelect { get; set; }

或更改您的 SelectList:

ViewBag.SingleSelectList = new SelectList(new[]
{
    new {ID="0",Name="-- Select --", Value=""},
    new {ID="1",Name="Select 1"},
    new{ID="2",Name="Select 2"},
    new{ID="3",Name="Select 3"},
},
"ID", "Name", 0);
于 2013-06-11T19:58:16.317 回答