Thursday, April 17, 2014

Sliding checkbox for MVC4

Sliding checkbox for MVC4

Requirement:

Show the checkbox as a slider and allow user to check or uncheck the option, save the updation in the database.




Solution:

For the CSS:
.checkSwitch {
       position: relative;
       margin: 4px 0 0 2px;
       width: 70px;
       height: 21px;
       border-radius: 3px;
       box-shadow: 0 0 0 1px rgba(0,0,0,0.3), 0 1px 0 1px rgba(255,255,255,0.3);
       cursor: pointer;
       overflow: hidden;
       display: inline-block;
       background: #e9e9e9;
}

.checkSwitch:hover {
      
}

.checkSwitch input {
       position: absolute;
       z-index: -1;
       opacity: 0;
       margin: 0;
       padding: 0;
       width: 100%;
       height: 100%;
}

.checkSwitchInner {
       position: absolute;
       top: 0;
       left: -45px;
       width: 115px;
       height: 100%;
       -webkit-transition: all .2s ease;
       -moz-transition: all .2s ease;
       -o-transition: all .2s ease;
       transition: all .2s ease;
}

.checkSwitch.on .checkSwitchInner {
       left: 0;
}

.checkSwitchOn, .checkSwitchOff, .checkSwitchHandle {
       width: 45px;
       height: 100%;
       font-family: Arial, Tahoma, sans-serif;
       font-size: 12px;
       text-align: center;
       line-height: 22px;
       font-weight: 100;
       color: #ffffff;
       text-shadow: -1px -1px 0 rgba(0,0,0,0.15);
       float: left;
}

.checkSwitchOn, .checkSwitchOff {
       box-shadow: inset 0 0 10px rgba(0,0,0,0.1);
}

.checkSwitchOn {
       position: relative;
       border-radius: 2px 0 0 2px;
       background: #4CA1FF;
}

.checkSwitchOff {
       position: relative;
       border-radius: 0 2px 2px 0;
       background: #aaaaaa;
}

.checkSwitchHandle {
       position: relative;
       width: 25px;
       font-size: 16px;
       line-height: 23px;
       font-weight: 100;
       color: #4b4b4b;
       text-shadow: none;
       border-radius: 3px;
       box-shadow: inset 0 -16px 20px -10px rgba(0,0,0,0.12);
       background: #ffffff url('drag_handle.png') center 6px no-repeat;
}




For the JQuery:
function checkSwitch()
{
       $('input.checkSwitch').each(function() {

              if($(this).attr('checked') == 'checked'){
                     $(this).wrap('<div class="checkSwitch on" />');
              } else {
                     $(this).wrap('<div class="checkSwitch off" />');
              }

              $(this).parent('div.checkSwitch').each(function() {
                     $(this).append('<div class="checkSwitchInner"><div class="checkSwitchOn"></div><div class="checkSwitchHandle"></div><div class="checkSwitchOff"></div></div>');
              });

       });
}

$(document).on('click', 'div.checkSwitch', function() {

       var $this = $(this);

       if($this.hasClass('off')){
              $this.addClass('on');
              $this.removeClass('off');
              $this.children('input.checkSwitch').attr('checked', 'checked');
       } else if($this.hasClass('on')){
              $this.addClass('off');
              $this.removeClass('on');
              $this.children('input.checkSwitch').removeAttr('checked');
       }


});


The code for the CSS and Jquery has been taken from http://labs.lukepeters.me/iphone-checkbox-switch/


In the View:

insert the checkSwitch();  function after the checkbox has been rendered,

@section JavaScript{
<script type="text/javascript" src="../../Scripts/checkswitch.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
         checkSwitch();
     });

    </script>
}

This is how the Checkbox is used,
Here HtmlHelper for checkbox is used with the first argument taking the (string)name attribute, second argument taking the (bool) isChecked attribute, third argument is the class name for our css.
         
@using(Html.BeginForm("ActionMethod","Controller",FormMethod.Post,new{id="grpForm"}))
{
    <div>
 <div>@Html.CheckBox(group.GroupName + "_" + group.Id.ToString(), group.IsSelected, new { @class = "checkSwitch"})</div>                                                
                                </div>

}



In the Model:

//model for selection
    public class Selection
    {
        public int Id { get; set; }
        public String SelectionName { get; set; }

        //Boolean value to select a checkbox on the list
        public bool IsSelected { get; set; }

        public Selection ()
        {
            this.Id = 0;
            this. SelectionName = String.Empty;
        }
    }




The method to get all the selections and showing which of them is checked/                                                                                                                                                                                                                                                                                                                                                                   unchecked
This is also a part of the model
public static List<Selection> GetAvailableSelections()
{
                           var dbExists = your linq query to get the record for     each option

                            if (dbExists != null)
                            {
                                avlgrp.IsSelected = true;
                            }
                            else
                            {
                                avlgrp.IsSelected = false;
                            }                         
                        }


For saving the Selections

  public static void SaveSelections(List<int> groupIdT, List<int> groupIdF,int leadid)
        {

            try
            {
                //for updating the current selection of tags/groups
                foreach (var gid in groupIdT)
               {
                   
                    //open the connection
                    using (SWSData db = new ef.SWSData())
                    {
                        //get the row to be updated
                        var dbGroup = db.Selections.SingleOrDefault(ld => ld.LeadId == leadid && ld.groupid == gid);

                        if (dbGroup != null)
                        {

                        }
                       
                        //if the selection does not exist already, insert a new record for the same.
                        else
                        {
                             Selection gc = new Selection()
                            {
                                groupid = gid,
                               LeadId = leadid
                              
                            };

                            db.AddToSelections(gc);

                            //save changes to database
                            db.SaveChanges();
                        }
                    }
                }

                //for deleting unselected selections from the database
                foreach (var gid in groupIdF)
                {

                   //open the connection
                    using (SWSData db = new ef.SWSData())
                    {
                        //get the row to be updated
                        var dbGroup = db.Selections.SingleOrDefault(ld => ld.LeadId == leadid && ld.groupid == gid);

                        if (dbGroup != null)
                        {
                            db.DeleteObject(dbGroup);
                            //save the changes to the database.
                            db.SaveChanges();
                        }
                    
                    }
                }

            }

            catch (Exception ex)
            {

                if (HttpContext.Current.IsDebuggingEnabled)
                {

                    throw ex;
                }
            }

        }





For the Controller:

[HttpPost]
[ActionName("Selection")]
        public ActionResult Selection_Post(int id, FormCollection form)
        {
            try
            {
               List<int> GrpIdsT = new List<int>();
               List<int> GrpIdsF = new List<int>();
               int gidt, gidf = 0;

               //loop through the form collection
                foreach (string key in form.Keys)
                {
                   //If the Selection is checked then add the selectionid to the list-GrpIdsT
                    bool isCheckedT = form[key].Contains("true");
                    if (isCheckedT)
                    {
//split the key on ‘_’                       
string[] st = key.Split('_');
                        gidt = Convert.ToInt32(st[1]);

                        GrpIdsT.Add(gidt);
                    }

                    //If the group is unchecked then add the selectionid to the list-GrpIdsF
                    else
                    {
                        string[] st = key.Split('_');
                        gidf = Convert.ToInt32(st[1]);

                        GrpIdsF.Add(gidf);
                    }
                }
              

                //save list of selections
                Repository.SaveSelections(GrpIdsT, GrpIdsF, id);

                   Return View();
  }
            catch (Exception ex)
            {

                ViewBag.ErrorMessage = "ERROR:" + ex.Message;
                return View("Error");
            }

}


No comments:

Post a Comment