1

Consider the following simple model:

public class TestClass {
    [MyRequired(ErrorMessage = "Some error message")]
    public int TestVariable { get; set; }
}

This will implicitly add the [Required] attribute and the rendered html will contain data-val attributes for both [Required] and [MyRequired].

I found 2 possible solutions:

// Solution #1 (.net 5 only)
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

// Solution #2
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

Unfortunately the first solution is not available for .net 6 and the second solution doesn't seem to work (propably because int is a value type and not a reference type?)

Finally I was able to solve this by making the TestVariable nullable:

public int? TestVariable { get; set; }

Not sure if this is good practice. Is there any way to disable this behavior globally without making everything nullable?

DimChtz
  • 4,043
  • 2
  • 21
  • 39
  • Re "not sure this is good practice": in an NRT context where values are not required, the only state you have left is `null`. It's fine practice (IMO) when you have NRT enabled since C# doesn't support discriminated unions natively. You're at least explicit about the possibility of the value being `null` when no value is provided which jives with the reason NRT is a thing to begin with. – D M Jun 07 '22 at 19:47
  • @DM You are right but keep in mind that I don't really need these values to be nullable, I am just trying to switch the implicit required attribute with my own. Also if I go with the "make 'em all nullable" route I need to make changes to many models/controllers. – DimChtz Jun 07 '22 at 19:52
  • Fair point. There's [a similar question](https://stackoverflow.com/questions/60830412/what-exactly-does-mvcoptions-suppressimplicitrequiredattributefornonnullablerefe) that has an answer which points out that there is no meaningful difference between `default(int)` and `0`. Does setting a default value for your model's property get you around the implicit `[Required]`? Obviously, that still requires a model change and might break assumptions in your `[MyRequired]`, but... – D M Jun 07 '22 at 20:07
  • Already tried this, but weirdly enough it still adds the required attribute :( – DimChtz Jun 07 '22 at 20:14
  • I am thinking of a way to create an attribute that goes to the whole class and removes all required rules from the model. Would that (or something similar to this) be possible? – DimChtz Jun 07 '22 at 20:17

0 Answers0