Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to bind checkbox with enum values in MVC?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 7.73k
    Comment on it

    To bind checkbox with enum, we have to write some custom code. Here, below is the example of binding checkbox with enum.

     

    Suppose we have a enum EmployeeGroup

    public enum EmployeeGroup
        {
            [Display(Name = "Group 1")]
            Group1,
            [Display(Name = "Group 2")]
            Group2,
            [Display(Name = "Group 3")]
            Group3,
            [Display(Name = "Group 4")]
            Group4,
        }

     

    then we have to create another enum for a store its bool value i.e either the value is selected or not.

     public class EnumModel
        {
            public EmployeeGroup EmployeeGroup { get; set; }
            public bool IsSelected { get; set; }
        }

     

    and it is used in the main model as :

     public class EmployeeModel
        {
            public int Id { get; set; }
         
            public string Name { get; set; }
    		
            public List<EnumModel> CheckBoxEmployeeGroup { get; set; }
        }

     

    In Controller:

    We have to fill CheckBoxEmployeeGroup as below:

     public ActionResult View()
            {
                EmployeeModel model = new EmployeeModel();
    
                model.CheckBoxEmployeeGroup = new List<EnumModel>();
                foreach (EmployeeGroup employeeGroup in Enum.GetValues(typeof(EmployeeGroup)))
                {
                    model.CheckBoxEmployeeGroup.Add(new EnumModel() { EmployeeGroup = employeeGroup, IsSelected = false });
                }
                return View(model);
            }

     

    In View:

    Employee Group : 
      @for (int i = 0; i < Model.CheckBoxEmployeeGroup.Count; i++)
    	{
    	@Html.DisplayFor(m => m.CheckBoxEmployeeGroup[i].EmployeeGroup);
    	@Html.CheckBoxFor(m => m.CheckBoxEmployeeGroup[i].IsSelected);
    	@Html.HiddenFor(m => m.CheckBoxEmployeeGroup[i].EmployeeGroup);
    	}
     @Html.ValidationMessageFor(model => model.EmployeeGroup, "", new { @class = "text-danger" })

     

    Hope, this code will help you. Thanks

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: