MVC下拉列表要求字段验证不起作用

时间:2016-02-05 09:50:15

标签: c# asp.net-mvc asp.net-mvc-4 html.dropdownlistfor

我是MVC的新手,作为我工作的一部分,我需要通过必要的字段验证来验证下拉列表,我尝试了以下方式,但验证无效, 当我点击提交按钮而不选择下拉菜单时,验证无效。

型号:

[Required(ErrorMessage = "*Required")]
[Display(Name = "Environment")]
public int? Environment { set; get; }

控制器:

List<SelectListItem> environmentlist = new List<SelectListItem>();
environmentlist.Add(new SelectListItem { Text = "SIT", Value = "1" });
environmentlist.Add(new SelectListItem { Text = "UAT", Value = "2" });
environmentlist.Add(new SelectListItem { Text = "PROD", Value = "3" });
ViewBag.EnvironmentList = environmentlist;

查看:

@Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, String.Empty)
@Html.ValidationMessageFor(model => model.Environment)

2 个答案:

答案 0 :(得分:0)

这可以在您的代码中提供帮助,

Public ActionResult yourMethod()
{
     if (ModelState.IsValid)
     {
        // Your code
     }
     else
     {                
        return View("Same View");
     }  
}

详细了解ModelState.IsValid

答案 1 :(得分:0)

尝试以下

 @Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, new {required = "required"})