Wednesday, 26 November 2014

Create CheckBoxList In Asp.net MVC


There is not any specific object like ChechboxList in MVC. yes you can install package and work with it
but you can do it without installing package.

Let's take one example.

you want to display days like below. you can take seven checkbox and to get value of it written seven times code to whether it is checked or not
in cotroller. instead of written seven times just create list object and create for loop and all values at controller side.



Model:

In model create static list
 public class CheckBoxItem
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public string Label { get; set; }
        public bool Checked { get; set; }

    }



  public class EventModel
    {
        public EventModel()
        {
            WeekDays = DaysList();
        }

public List<CheckBoxItem> WeekDays { get; set; }

  public static List<CheckBoxItem> DaysList()
        {
            var list = new[]
            {
              new CheckBoxItem { Name = "Sunday", Value = "1", Label = "Sunday", Checked = false},
              new CheckBoxItem { Name = "Moday", Value = "2", Label = "Moday", Checked = false},
              new CheckBoxItem { Name = "Tuesday", Value = "3", Label = "TuesDay", Checked = false},
              new CheckBoxItem { Name = "Wednesday", Value = "3", Label = "Wednesday", Checked = false},
              new CheckBoxItem { Name = "Thursday", Value = "3", Label = "Thursday", Checked = false},
              new CheckBoxItem { Name = "Friday", Value = "3", Label = "Friday", Checked = false},
              new CheckBoxItem { Name = "Saturday", Value = "3", Label = "Saturday", Checked = false},

            };
            return list.ToList();
        }

}


View:

@for (int i = 0; i < EventTest.Models.EventModel.DaysList().Count(); i++)
         {
                 @Html.CheckBoxFor(m => m.WeekDays[i].Checked, new { id = @EventTest.Models.EventModel.DaysList()[i].Value })
                 @EventTest.Models.EventModel.DaysList()[i].Name
        }

Controller:
  public ActionResult CreateEvent(EventTest.Models.EventModels e)
        {
  for (int i = 0; i < e.RepeatType.WeekDays.Count; i++)
                    {
                        if (e.RepeatType.WeekDays[i].Checked)
                        {
                            ChkDayName += EventTest.Models.EventModel.DaysList()[i].Value + ",";
                        }
                    }
                        ChkDayName = ChkDayName.TrimEnd(',');
}

No comments:

Post a Comment