2013-12-16 20 views
2

查看DROPDOWNLIST客户端需要验证(不模型)

@Html.DropDownList("CategoryItems", null, new { @class = "ddlcs" }) 
@Html.ValidationMessage("CategoryItems") 

控制器

var cat = from s in db.CategoryDbSet 
      where s.IsActive == true 
      orderby s.CatName 
      select new { s.CatID, s.CatName }; 

var catListItems = cat.ToList() 
         .Select(c => new SelectListItem 
          { 
           Text = c.CatName, 
           Value = c.CatID.ToString() 
          }) 
         .ToList(); 

catListItems.Insert(0, new SelectListItem 
          { 
           Text = "[--Select the category--]", 
           Value = "" 
          }); 

ViewBag.CategoryItems = catListItems; 

我想执行的下拉所需的验证,当有人选择“选择保存操作中的类别“选项。我是新来的MVC框架,我不知道我在哪里犯了错误?此下拉列表不与模型绑定。

请建议soln。

回答

6

此下拉列表不与模型绑定。

这是错误。 ASP.NET MVC中的验证通过使用相应属性装饰您的视图模型属性进行工作。例如,如果您想要使用此下拉菜单,则可以使用[Required]属性在您的视图模型上修饰相应的属性。

所以添加必要的属性,以现有的视图模型:

public class MyViewModel 
{ 
    [Required] 
    public int? SelectedCategoryId { get; set; } 

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

    ... some other properties that your view might need 
} 

,然后在你的控制器动作填充这个视图模型:

var model = new MyViewModel(); 
model.Categories = cat 
    .ToList() 
    .Select(c => new SelectListItem 
    { 
     Text = c.CatName, 
     Value = c.CatID.ToString() 
    }).ToList(); 

return View(model); 

,并在您的视图中使用的强类型版本帮手:

@Html.DropDownListFor(
    x => x.SelectedCategoryId, 
    Model.Categories, 
    "[--Select the category--]", 
    new { @class = "ddlcs" } 
) 
@Html.ValidationMessageFor(x => x.SelectedCategoryId) 
+0

感谢您的帮助。但我使用EF来将db对象映射到模型中。无论我在哪里使用此模型,我都会在其他地方收到错误消息。 System.Data.SqlClient.SqlException:无效的列名称'SelectedCategoryId'。 – Karan

+0

现在我怎么能够修复这个新的属性为其他地方。 – Karan

+2

您不应在视图中使用您的EF模型。这就是视图模型的目的。你的控制器可以在2. –

0

如果你只想客户端验证,你可以这样做:

$('form').validate({ 
    rules:{ 
     CategoryItems: 'required' 
    } 
}); 

Working demo

但我不会建议这样做,因为客户端验证是为了更好的用户体验,并且可以轻松绕过。 Darin的答案中描述了使用数据注解和视图模型的正确方法。

相关问题