在ASP.NET验证一个的SelectList MVC 2数据注释

问题描述:

我试图使用内置的ASP.NET MVC 2客户端验证在选择列表如下所示:在ASP.NET验证一个的SelectList MVC 2数据注释

private SelectList _CategoryList; 
     [Required(ErrorMessage = "Category Required")] 
     [System.ComponentModel.DataAnnotations.Range(1, double.MaxValue, ErrorMessage = "Please Select A Category")] 
     [DisplayName("Category")] 
     public SelectList CategoryList 
     { 
      get 
      { 
       return new SelectList(Categories, "CatID", "CatFullName"); ; 
      } 
      set 
      { 
       _CategoryList = value; 
      } 
     } 

但是这不是正在工作......如果选择默认值0,则验证消息不会出现,并且页面会像进行验证一样前进。思考?

+0

发现各种各样的答案:http://stackoverflow.com/questions/1047899/problems-with-asp-mvc-html-dropdownlist-using-a-modelview-pattern轻微的调整,它的工作原理...最大的缺点是我必须重新填充下拉,如果ModelState是无效的... – Webjedi 2010-01-20 22:20:33

+0

我问了一个与此相关的问题 http://stackoverflow.com/questions/2086999/null-values-from-listbox-are-not-evaluated-in-the-model-binding-of-asp-net-mvc – Jorge 2010-01-19 15:46:52

好,所以我找到了答案,在一个稍有不同的问题的答案。所以我张贴我在这里完整代码,它扩展了斯科特Guthries ASP.NET MVC 2验证后:http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

我的视图模型:

public class Person 
{ 
    [Required(ErrorMessage="First Name Required")] 
    [StringLength(50,ErrorMessage="Must be under 50 characters")] 
    public string FirstName { get; set; } 

    [Required(ErrorMessage="Last Name Required")] 
    [StringLength(50, ErrorMessage = "Must be under 50 characters")] 
    public string LastName { get; set; } 

    [Required(ErrorMessage="Age Required")] 
    [Range(1,120,ErrorMessage="Age Must be between 0 and 120")] 
    public int Age { get; set; } 

    [Required(ErrorMessage="Email Required")] 
    public string Email { get; set; } 


    public IEnumerable<SelectListItem> FavoriteColor { get; set; } 


    [Range(0, 6, ErrorMessage = "Out of range")] 
    public int SelectedFavColor { get; set; } 
} 

我的颜色类:

public class Colors 
{ 
    public int ColorID { get; set; } 
    public string ColorName { get; set; } 
} 

我从Rob Connery盗走的名单中,从谁偷走了他人:

public static class ListExtensions 
{ 
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection, Action<T> action) 
    { 
     foreach (var item in collection) action(item); 
     return collection; 
    } 

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection) 
    { 
     return new SelectList(collection, "Key", "Value"); 
    } 

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection, string selectedValue) 
    { 
     return new SelectList(collection, "Key", "Value", selectedValue); 
    } 

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection, 
         string dataValueField, string dataTextField) 
    { 
     return new SelectList(collection, dataValueField, dataTextField); 
    } 

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection, 
         string dataValueField, string dataTextField, string selectedValue) 
    { 
     return new SelectList(collection, dataValueField, dataTextField, selectedValue); 
    } 
} 

我的控制器代码(是的,它可以重构更DRY):

public ActionResult Create() 
    { 
     Person newFriend = new Person(); 
     IList<Colors> colorslist = new List<Colors>(); 
     colorslist.Add(new Colors { ColorID = -1, ColorName = "Please Select Color" }); 
     colorslist.Add(new Colors { ColorID = 1, ColorName = "Red" }); 
     colorslist.Add(new Colors { ColorID = 2, ColorName = "Green" }); 
     colorslist.Add(new Colors { ColorID = 3, ColorName = "Blue" }); 

     newFriend.FavoriteColor = colorslist.ToSelectList("ColorID","ColorName","-1"); 
     return View(newFriend); 
    } 

    [HttpPost] 
    public ActionResult Create(Person friendToCreate, FormCollection collection) 
    { 
     friendToCreate.SelectedFavColor = Convert.ToInt32(collection["SelectedFavColor"]); 
     if (ModelState.IsValid) 
     { 
      return Redirect("/"); 
     } 
     IList<Colors> colorslist = new List<Colors>(); 
     colorslist.Add(new Colors { ColorID = -1, ColorName = "Please Select Color" }); 
     colorslist.Add(new Colors { ColorID = 1, ColorName = "Red" }); 
     colorslist.Add(new Colors { ColorID = 2, ColorName = "Green" }); 
     colorslist.Add(new Colors { ColorID = 3, ColorName = "Blue" }); 
     friendToCreate.FavoriteColor = colorslist.ToSelectList("ColorID", "ColorName"); 
     return View(friendToCreate); 
    } 

我的页面标记:

<% using (Html.BeginForm()) {%> 

    <fieldset> 
     <legend>Fields</legend> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.FirstName) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.FirstName) %> 
      <%= Html.ValidationMessageFor(model => model.FirstName) %> 
     </div> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.LastName) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.LastName) %> 
      <%= Html.ValidationMessageFor(model => model.LastName) %> 
     </div> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.Age) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.Age) %> 
      <%= Html.ValidationMessageFor(model => model.Age) %> 
     </div> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.Email) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.Email) %> 
      <%= Html.ValidationMessageFor(model => model.Email) %> 
     </div> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.FavoriteColor) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.DropDownList("SelectedFavColor", Model.FavoriteColor, -1)%> 
      <%= Html.ValidationMessageFor(model => model.SelectedFavColor) %> 
     </div> 

     <p> 
      <input type="submit" value="Submit" /> 
     </p> 
    </fieldset> 

<% } %> 

我不认为它与DataAnnotations有关,因为它发生在没有它们的情况下,当你有一个模型绑定到一个不可为空的实体,并且你试图把一个无效值放入时。是从表单发送ModelState [“XXXX”]。Value.AttemptedValue,并根据该值进行验证,而不是实体中的属性。我想知道是否对原始表单数据进行完全验证,而不仅仅是问题项目更合适。

类似的答复:ASP.NET MVC: DataAnnotations - Show an error message indicating that a field must be numeric

我也提出了类似的问题:ASP.NET MVC. Validation fails on dropdown no matter the value

当我与我的ViewModel工作,我有一个属性类别编号,并把对我的范围验证,而不是下拉列表。选择列表只提供数据 - 您可以根据模型进行验证。

[Required(ErrorMessage = "Category Required")] 
    [System.ComponentModel.DataAnnotations.Range(1, double.MaxValue, ErrorMessage = "Please Select A Category")] 
    [DisplayName("Category")] 
    public int CategoryId {get;set;} 

在视图我有我的下拉与ID为我的类别但是从我类别列表:

<%= Html.DropDownList("CategoryId", (SelectList)Model.Categories, "(Select)")%>  

当你的数据回发到服务器,你应该观察到类包含id值。

+1

W当我尝试你的代码时,它告诉我CategoryId是int类型的,但它需要是一个IEnumerable 。所以我改变了它......但后来认为每个值都是一个字符串。 Hmmmm – Webjedi 2010-01-20 16:07:57