我有一个具有以下属性的模型:
[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>
如果用户未在表单提交上做出选择(仍然在选项“ - 选择 - ”),如何在显示错误的情况下进行验证?
答案 0 :(得分: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);