System.InvalidOperationException when attempting to use custom validation attribute

2

I am trying to add a checkbox that must be ticked to progress, a standard terms and conditions declaration.

Looking around the web, all answers to the problem are some variation of the following code:

[Display(Name = "This Is A Test")]
[MustBeTrue(ErrorMessage = "come on!")]
//[MustBeTrue(ErrorMessageResourceType = typeof(Res.Text), ErrorMessageResourceName = "ValidationMessage")]
//[Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
public bool TermsAndConditions { get; set; }

the custom attribute looks like this:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return value is bool && (bool)value;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "mustbetrue"
        };
    }
}

and then something akin to:

$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");

In my view I am rendering the checkbox like so:

@Html.CheckBoxFor(m => m.TermsAndConditions, false)
@Html.LabelFor(m => m.TermsAndConditions)
@Html.ValidationMessageFor(m => m.TermsAndConditions)

I've tried a wealth of variations on this, and I always hit the same exception:

System.InvalidOperationException
  HResult=0x80131509
  Message=The parameter conversion from type 'System.String' to type 'Nordics.Models.PolicyManagement.Affiliates.Affiliate' failed because no type converter can convert between these types.
  Source=System.Web.Mvc
  StackTrace:
   at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)

I am at a complete loss, can someone point me in the right direction? Thanks.

c#
.net
asp.net-mvc
validation
asp.net-mvc-5

1 Answer

0

So it turns out the described is a non issue. I am not quite sure what the exception at this point but it was there well before the new validation code. The validation code is actually working as it should, however due to the way the site is built, it's trying to validate the model before we can see the view and thus the view never loads because the checkbox always starts as false.

answered on Stack Overflow Mar 14, 2019 by monkeySeeMonkeyDo

User contributions licensed under CC BY-SA 3.0