使用(Html.ValidationMessage)对mvc中的下拉列表进行简单验证

时间:2011-07-11 13:59:52

标签: asp.net-mvc asp.net-mvc-2 validation asp.net-mvc-3

控制器

var productList = Enumerable.Range(1, 80).Select(
    x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }
);
ViewData["products"] = new SelectList(productList.ToList(), "Value", "Text");

查看

<%: Html.DropDownList("products", ViewData["products"] as SelectList, "--select--")%>
<%: Html.ValidationMessage("products", "Please Select the Product from the List")%> 
//This doesnt works on (ModelState.IsValid) I know the dropdown list data is coming
//from the view data not model , thats why model doesnt validate the particular dropdown 
//list while it validates other fields which are linked to model,
//Just want to know, how can i validate the above dropdownlist 

1 个答案:

答案 0 :(得分:11)

您将ddl的名称和值绑定到products。那是错的。当然,这是您的代码最少的问题。更大更严重的问题是您使用ViewData而不是使用强类型视图和视图模型。

所以有两种可能性:

  1. 糟糕的一个:在您的视图模型上有一个属性,您将绑定您的下拉值。

    [Required(ErrorMessage = "Please Select the Product from the List")]
    public string SelectedProduct { get; set; }
    

    然后将此属性名称用作弱类型DropDownList助手的第一个参数,将ViewData用作第二个agrument:

    <%= Html.DropDownList( 
        "SelectedProduct", 
        ViewData["products"] as SelectList, 
        "--select--"
    ) %>
    <%= Html.ValidationMessage("SelectedProduct") %>
    
  2. 正确的方法:当然是使用真实视图模型(我厌倦了重复它,只是google,你会得到gazillions of answers,就像我一样,只是在这个网站上话题)。它看起来像这样:

    <%: Html.DropDownListFor( 
        x => x.SelectedProduct, 
        Model.Products, 
        "--select--"
    ) %>
    <%= Html.ValidationMessageFor(x => x.SelectedProduct) %>