Limit the checkbox checked to only one item in IList

Vote:
 

I have created a IList given as below:

[CultureSpecific]
[Display(Name = "Items", GroupName = PropertyGroupNames.Content, Order = 20)]
[EditorDescriptor(EditorDescriptorType = typeof(AnswerListPropertyDescriptor))]
[ListItems(4)]

public virtual IList<AnswerBlock> Answers { get; set; }

AnswerBlock is a class I have created:

public class AnswerBlock
{
[CultureSpecific]
[Display(Name = "Answer Text", GroupName = PropertyGroupNames.Content, Order = 10)]
public virtual string AnswerText { get; set; }

[CultureSpecific]
[Display(Name = "Correct Answer", GroupName = PropertyGroupNames.Content, Order = 20)]

public virtual bool IsCorrect { get; set; }
}

IsCorrrect is a type of a checkbox

I add multiple elements in the dropdownlist created due to IList

The problem is that II'm able to set true to multiple checkboxes present in the IList

I just want to limit it upto 1. i.e I should only be able to set 1 checkbox to true in IList.

Please help

#223847
Jun 05, 2020 6:22
Vote:
 

Hi,

You should be able to do this through validation by creating a custom ValidationAttribute to ensure only 1 item has that property set. Something like this:

public class CustomIListValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var list = value as IList<AnswerBlock>;
        return list.Count(x => x.IsCorrect) > 0 ? new ValidationResult($"Only one option can be flagged as Correct") : null;
    }
}

You could then apply the validator to your IList property like this:

[CultureSpecific]
[Display(Name = "Items", GroupName = PropertyGroupNames.Content, Order = 20)]
[EditorDescriptor(EditorDescriptorType = typeof(AnswerListPropertyDescriptor))]
[ListItems(4)]
[CustomIListValidator]
public virtual IList<AnswerBlock> Answers { get; set; }
#223856
Edited, Jun 05, 2020 9:05
Vote:
 
return list.Count(x => x.IsCorrect) > 1 ? new ValidationResult($"Only one option can be flagged as Correct") : null;
#223859
Jun 05, 2020 10:33
Vote:
 

Ah, yes. Well spotted Tomas. The code is there more as an example rather than a copy/paste solution so looks like I missed that.

Thinking about it though, it looks like this is a question & answer scenario where I would imagine you would have to define a single correct answer so perhaps it should actually be:

return list.Count(x => x.IsCorrect) != 1 ? new ValidationResult($"A single option must be flagged as Correct") : null;
#223860
Jun 05, 2020 10:58
Tanvi - Jun 10, 2020 8:40
Its working!!!!!
Paul Gruffydd - Jun 10, 2020 8:48
Good stuff. Glad to hear it.
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.