如何验证DropDownListFor与列表绑定的值

时间:2013-08-29 10:20:43

标签: c# asp.net-mvc-4 razor-2

我想验证DropDownListFor中的值,但它不起作用。我也包含了客户端验证所需的脚本文件。

在ViewModel中:

public class SearchViewModel
{
    public List<MarriageProfile> Profiles { get; set; }
    public SearchProfile SearchProfile { get; set; }
}

public class SearchProfile
{
    [Required(ErrorMessage="*")]
    public SelectList Ages { get; set; }
    public string Age { get; set; }
}

在控制器中:

var ages = AgeList
           .Select(p => new SelectListItem()
           {
               Text = p.ToString(),
               Value = p.ToString()
           }).ToList();

SearchViewModel.SearchProfile.Ages = new SelectList(ages, "Text", "Value");

static List<string> AgeList = new List<string>()
{        
    "18-23",
    "23-28",
    "28-33",
    "33-38",
    "38-43",
    "43-48"
};

在视图中:

@Html.DropDownListFor(model => model.Age, Model.Ages, "--Select One--", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Age)

在提交表单时,上面的下拉列表中没有客户端或服务器端验证。代码有什么问题?

1 个答案:

答案 0 :(得分:1)

您似乎需要使用Age属性标记Required属性,而不是Ages列表。看看这个答案:ASP.NET MVC 3 and validation attribute for dropdownlist with default value of 0