i have showing many checkboxes for hobbies property in view model but i like to attach ValidationMessageFor as a result user should be force to select any one checkbox out of many.
so here is model & viewmodel
public class Hobby
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class SampleViewModel
{
[Required(ErrorMessage = "Select any Hobbies")]
public List<Hobby> Hobbies { get; set; }
}
action method code
public ActionResult Index()
{
var SampleVM = new SampleViewModel();
SampleVM.Products = new List<Product>
{
new Product{ ID=1, Name="IPhone" },
new Product{ ID=2, Name="MacBook Pro" },
new Product{ ID=3, Name="iPod" }
};
SampleVM.Hobbies = new List<Hobby>()
{
new Hobby(){ Name = "Reading", IsSelected= false },
new Hobby(){ Name = "Sports" ,IsSelected= false},
new Hobby(){ Name = "Movies" ,IsSelected= false}
};
return View(SampleVM);
}
[HttpPost]
public ActionResult Index(SampleViewModel vm)
{
ViewBag.IsPostBack = false;
if (ModelState.IsValid)
{
Product p = vm.Products.Where(x => x.ID == vm.SelectedProductId).FirstOrDefault();
ViewBag.IsPostBack = true;
ViewBag.ProductID = p.ID.ToString();
ViewBag.ProductName = p.Name.ToString();
return View(vm);
}
else
{
var SampleVM = new SampleViewModel();
SampleVM.Products = new List<Product>
{
new Product{ ID=1, Name="IPhone" },
new Product{ ID=2, Name="MacBook Pro" },
new Product{ ID=3, Name="iPod" }
};
SampleVM.Hobbies = new List<Hobby>()
{
new Hobby(){ Name = "Reading", IsSelected= false },
new Hobby(){ Name = "Sports" ,IsSelected= true},
new Hobby(){ Name = "Movies" ,IsSelected= true}
};
return View(SampleVM);
}
view code
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<b>Hobbies</b><br />
@for (int x = 0; x < Model.Hobbies.Count(); x++)
{
@Html.CheckBoxFor(p => p.Hobbies[x].IsSelected) @:
@Html.LabelFor(p => p.Hobbies[x].IsSelected, Model.Hobbies[x].Name) @:
}
</div>
@Html.ValidationMessageFor(model => model.Hobbies, "", new { @class = "text-danger" })
</div>
so tell me what to change in code as a result validation message will fire if user select no check boxes for hobbies.
thanks
ValidationAttribute(but this will work server side only, - its not possible to get client side validation for a collection usingjquery.validate.unobtrusive