Click here to Skip to main content
15,886,110 members
Home / Discussions / ASP.NET
   

ASP.NET

 
QuestionCommunication with comport in ASP.Net VB Pin
Member 112927873-Apr-16 3:05
Member 112927873-Apr-16 3:05 
QuestionI Had High Hopes for Metro-UI - But Pin
xiecsuk31-Mar-16 23:13
xiecsuk31-Mar-16 23:13 
QuestionNested Gridview need help. Pin
hmanhha30-Mar-16 6:43
hmanhha30-Mar-16 6:43 
AnswerRe: Nested Gridview need help. Pin
User 418025411-Apr-16 8:32
User 418025411-Apr-16 8:32 
QuestionHow do i add new json file in VS2012? Pin
King Fisher27-Mar-16 23:43
professionalKing Fisher27-Mar-16 23:43 
AnswerRe: How do i add new json file in VS2012? Pin
ZurdoDev28-Mar-16 7:33
professionalZurdoDev28-Mar-16 7:33 
QuestionMVC @Helpers, reusable HTML in a view, to place in App_Code? Pin
jkirkerx27-Mar-16 11:46
professionaljkirkerx27-Mar-16 11:46 
QuestionASP.Net MVC: custom client side validation for checkboxes is not working Pin
Tridip Bhattacharjee27-Mar-16 1:27
professionalTridip Bhattacharjee27-Mar-16 1:27 
basically i am showing checkboxes in page and checkboxes generated in loop. i have create a custom validation using this

ValidationAttribute, IClientValidatable

my server side validation working fine but client side is not firing. please have a look at my code and tell me where i made the mistake.
My Goal

i want user has to select one hobby means user has to select one check boxes out of many.
this way i am generating checkboxes
HTML
<div class="col-md-offset-2 col-md-10">
    Hobbies<br />
    @for (int x = 0; x < Model.Hobbies.Count(); x++)
    {
        @Html.CheckBoxFor(p => p.Hobbies[x].IsSelected) @:  
        @Html.LabelFor(p => p.Hobbies[x].IsSelected, Model.Hobbies[x].Name) @:  
        @Html.HiddenFor(p => p.Hobbies[x].Name)
    }
    @Html.ValidationMessageFor(model => model.Hobbies)
</div>


this way i annotate my view model property

C#
[AtleastOne(ErrorMessage = "Select at least one checkbox.")]
public List<Hobby> Hobbies { get; set; }


here is code for custom validation.
C#
public class AtleastOneAttribute : ValidationAttribute, IClientValidatable
{
    // For Server side
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var oHobby=value as IEnumerable;

            foreach (var _object in oHobby)
            {
                Hobby _oHobby = (Hobby)_object;
                if (_oHobby.IsSelected)
                {
                    return ValidationResult.Success;
                }
            }

        }
        return new ValidationResult(ErrorMessage);
    }
    // Implement IClientValidatable for client side Validation
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "atleastonetrue",
        };
        yield return rule;
    }
}


client side code
JavaScript
<script type="text/javascript">

    $.validator.unobtrusive.adapters.add('atleastonetrue',  function (options) {
        //options.rules['restrictbackdates'] = { mindate: options.params.mindate };
        options.messages['atleastonetrue'] = options.message;
        alert('hello');
        alert(options.message);
    });

    $.validator.addMethod("atleastonetrue", function (value, element, param) {
        alert('hello');

        //var date = new Date(value);
        //var minDate = new Date(param.mindate);
        //return date >= minDate;
    });
</script>


where i made the mistake in my code for which client side code is not firing?
Generated html for checkbox
HTML
<div class="col-md-offset-2 col-md-10">
                Hobbies<br>
<input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies_0__IsSelected" data-val-required="The IsSelected field is required." data-val="true"><input type="hidden" value="false" name="Hobbies[0].IsSelected">    
<label for="Hobbies_0__IsSelected">Reading</label>   
<input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name"><span data-valmsg-replace="true" data-valmsg-for="Hobbies[0].IsSelected" class="field-validation-valid"></span><input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies_1__IsSelected" data-val-required="The IsSelected field is required." data-val="true"><input type="hidden" value="false" name="Hobbies[1].IsSelected">    
<label for="Hobbies_1__IsSelected">Sports</label>   
<input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name"><span data-valmsg-replace="true" data-valmsg-for="Hobbies[1].IsSelected" class="field-validation-valid"></span><input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies_2__IsSelected" data-val-required="The IsSelected field is required." data-val="true"><input type="hidden" value="false" name="Hobbies[2].IsSelected">    
<label for="Hobbies_2__IsSelected">Movies</label>   
<input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name"><span data-valmsg-replace="true" data-valmsg-for="Hobbies[2].IsSelected" class="field-validation-valid"></span>                
            </div>


My Model and ViewModel
C#
public class Product
  {
      public int ID { set; get; }
      public string Name { set; get; }
  }

  public class Hobby
  {
      public string Name { get; set; }
      public bool IsSelected { get; set; }

  }

  public class SampleViewModel
  {
      [Display(Name = "Products")]
      public List<Product> Products { set; get; }

      [AtleastOne(ErrorMessage = "Select at least one checkbox.")]
      public List<Hobby> Hobbies { get; set; }

      [Required(ErrorMessage = "Select any Product")]
      public int SelectedProductId { set; get; }

      [Required(ErrorMessage = "Select Male or Female")]
      public string Gender { get; set; }
  }

thanks
tbhattacharjee

SuggestionRe: ASP.Net MVC: custom client side validation for checkboxes is not working Pin
Richard Deeming29-Mar-16 2:17
mveRichard Deeming29-Mar-16 2:17 
QuestionWHere to put JavaScrip in ASP.net Pin
hmanhha26-Mar-16 8:33
hmanhha26-Mar-16 8:33 
AnswerRe: WHere to put JavaScrip in ASP.net Pin
F-ES Sitecore27-Mar-16 5:02
professionalF-ES Sitecore27-Mar-16 5:02 
GeneralRe: WHere to put JavaScrip in ASP.net Pin
hmanhha28-Mar-16 7:22
hmanhha28-Mar-16 7:22 
GeneralRe: WHere to put JavaScrip in ASP.net Pin
F-ES Sitecore28-Mar-16 7:38
professionalF-ES Sitecore28-Mar-16 7:38 
QuestionMVC5 WebGrid styling issues Pin
#realJSOP24-Mar-16 3:22
mve#realJSOP24-Mar-16 3:22 
AnswerRe: MVC5 WebGrid styling issues Pin
#realJSOP24-Mar-16 7:26
mve#realJSOP24-Mar-16 7:26 
AnswerRe: MVC5 WebGrid styling issues Pin
#realJSOP24-Mar-16 7:48
mve#realJSOP24-Mar-16 7:48 
GeneralRe: MVC5 WebGrid styling issues Pin
Brisingr Aerowing24-Mar-16 17:10
professionalBrisingr Aerowing24-Mar-16 17:10 
GeneralRe: MVC5 WebGrid styling issues Pin
#realJSOP25-Mar-16 0:47
mve#realJSOP25-Mar-16 0:47 
GeneralRe: MVC5 WebGrid styling issues Pin
Brisingr Aerowing25-Mar-16 4:41
professionalBrisingr Aerowing25-Mar-16 4:41 
QuestionMVC/EF typical/best practice Pin
#realJSOP24-Mar-16 1:21
mve#realJSOP24-Mar-16 1:21 
AnswerRe: MVC/EF typical/best practice Pin
Nathan Minier24-Mar-16 1:37
professionalNathan Minier24-Mar-16 1:37 
GeneralRe: MVC/EF typical/best practice Pin
#realJSOP24-Mar-16 2:02
mve#realJSOP24-Mar-16 2:02 
GeneralRe: MVC/EF typical/best practice Pin
Nathan Minier24-Mar-16 2:08
professionalNathan Minier24-Mar-16 2:08 
GeneralRe: MVC/EF typical/best practice Pin
John C Rayan24-Mar-16 5:27
professionalJohn C Rayan24-Mar-16 5:27 
GeneralRe: MVC/EF typical/best practice Pin
Richard Deeming24-Mar-16 2:14
mveRichard Deeming24-Mar-16 2:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.