Saturday, April 26, 2014

How to use Checkbox with Validation in MVC4


Here I have created View for Checkbox

  <div class="controls">
                        @{                
                foreach (var i in @UserData.FetchDictionaryDataByName("DeliveryModeDict"))
                {
                   <div class="checkbox-new">
                  <input type="checkbox"  name="DeliveryMode" value="@i.Key"  id="chkDeliveryMode"  class="checkbox-input"  @UserData.CheckedMode(@i.Key, @Model.DeliveryMode) />
                        <label>@i.Value</label>
                   </div>
                }
                        }
              @Html.ValidationMessageFor(m => m.DeliveryMode, string.Empty, new { @class = "validation-error" })
        </div>


This function is generate checkboxes value. i have created Dictionary for those values so i will pass that dictionary name then it will return keys and values. 


 public static Dictionary<string, string> FetchDictionaryDataByName(string DictName)
        {
            string cultureLanguage = ProjectUtils.SetCulureInfo();
            List<KeyVal> keyVal = new List<KeyVal>();
            Dictionary<string, string> obj = MasterDictUtil.FetchSingleDictByName(DictName, cultureLanguage);
            if (obj != null)
            {
                return obj;
            }
            return null;
        }



Javascript Function for server side validation


 function DeliveryModeChecked() {
            var fields = $("input[name='DeliveryMode']").serializeArray();
            if (fields.length == 0) {
                 alert('Select atleast one checkbox value');        
                return false;
            }
            else {
                // alert(fields.length + " items selected");
                 return true;
            }
        }



This function which i have used for selected checkbox at the edit time 


 public static string CheckedMode(string input, List<string> CheckMode)
        {
            string ckChecked = "";
            if (CheckMode != null && CheckMode.Count > 0)
            {
                if (CheckMode.Contains(input))
                {
                    ckChecked = "checked=\"checked\"";
                }
            }
            return ckChecked;
        }



Now you just create action in controller and call from view on submit form using @Html.Beginform

OnSubmit call DeliveryModeChecked() function

No comments:

Post a Comment