خرید بک لینک

Vote count: 0

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.Hobbies = new List<Hobby>()
            {
                new Hobby(){ Name = "Reading", IsSelected= false },
                new Hobby(){ Name = "Sports" ,IsSelected= false},
                new Hobby(){ Name = "Movies" ,IsSelected= false}
            };
            retu 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) @: &nbsp; 
            @Html.LabelFor(p => p.Hobbies[x].IsSelected, Model.Hobbies[x].Name) @: &nbsp;
        }
    </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

asked 4 mins ago

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 5 فروردين 1395 ساعت: 19:28

صفحه بندی