在MVC 4中验证单个选择下拉

本文关键字:选择 单个 验证 MVC | 更新日期: 2023-09-27 18:17:59

我有一个模型,它有如下属性:

[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>

我怎么能得到验证工作显示一个错误,如果用户没有选择表单提交(仍然在选项"——选择——")?

在MVC 4中验证单个选择下拉

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

[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);