Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to show checkbox selected using MVCCheckBoxList in Asp.Net MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 672
    Comment on it

    How to show checkbox selected using MVCCheckBoxList in Asp.Net MVC

    In my previous blog I have discussed about how to use MVCCheckBoxList. Please visit the following link for reference:

    MVCCheckBoxList in Asp.Net MVC

    The problem which I also faced while using MVCCheckBoxList is to show the checkbox selected, when directed to another page after selecting the CheckBoxes. We are always getting the blank CheckBoxes.

    The solution which I got for the above problem is as follows:

    Let us take a Model class for the MVCCheckBoxList :

    public class RegisterationModel
            public IEnumerable<SelectListItem> chkbx { get; set; }
            public string[] chkbxIds { get; set; }

    As discussed in the above mentioned blog to bind the CheckBoxList we use to write the following code :

     IEnumerable<Models.RegisterationModel.CheckBoxOptions> checkBoxOptions = Enum.GetValues(typeof (Models.RegisterationModel.CheckBoxOptions)) .Cast<Models.RegisterationModel.CheckBoxOptions>();
      model.chkbx = from action in checkBoxOptions
                                  select new SelectListItem 
                                      Text = action.ToString(),
                                      Value = ((int)action).ToString()

    As discussed in my previous blog public string[] chkbxIds { get; set; } holds the index of the selected CheckBoxes, therefore inorder to show the CheckBoxes selected replace the above code for binding the CheckBoxList :

    IEnumerable<RegisterationModel.CheckBoxOptions> checkBoxOptions = Enum.GetValues(typeof (RegisterationModel.CheckBoxOptions)) .Cast<RegisterationModel.CheckBoxOptions>();
                    List<SelectListItem> list = new List<SelectListItem>();
                    foreach (var action in checkBoxOptions)
                        var select = new SelectListItem();
                        select.Text = action.ToString();
                        select.Value = ((int)action).ToString();
                        if (model.chkbxIds.Contains(select.Value))
                             select.Selected = true;
                    model.chkbx = list;

    Note=>This will check if model.chkbxIds holds the value (i.e the value of the selected checkbox), It will show that Checkbox Checked.

    Hope it helps...!

 0 Comment(s)

Sign In

Sign up using

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: