AI OnAI Off
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; }
return list.Count(x => x.IsCorrect) > 1 ? new ValidationResult($"Only one option can be flagged as Correct") : null;
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;
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