How can my modelstate be invalid when there are no constraints on it?


My ViewModel looks like this:

public class BookingViewModel
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }        
    public DateTime CheckInDate { get; set; }
    public DateTime CheckOutDate { get; set; }
    //Need this to display which room was chosen by the user
    public RoomTypeDTO? RoomType { get; set; }
    public int RoomTypeId { get; set; }


The view looks (partly) like this:

        <label asp-for="FirstName"></label>
        <input asp-for="FirstName" class="col-xs-4"/>
        <span asp-validation-for="FirstName" class="text-danger"></span>
    <br />
        <label asp-for="LastName"></label>
        <input asp-for="LastName" class="col-xs-4" />
        <span asp-validation-for="LastName" class="text-danger"></span>

When the ViewModel is sent from this view to the controller action Create, if I don’t input anything in FirstName and LastName textboxes, I get invalid modelstate and then the default errors "First Name is required"

How can this be happening? It’s conflicting with my fluent validation.

>Solution :

By default, non-nullable types are treated as-if they are decorated with the [Required] attribute.

From the docs Non-nullable reference types and the [Required] attribute:

The validation system treats non-nullable parameters or bound
properties as if they had a [Required(AllowEmptyStrings = true)]
attribute. By enabling Nullable contexts, MVC implicitly starts
validating non-nullable properties on non-generic types or parameters
as if they had been attributed with the [Required(AllowEmptyStrings =
true)] attribute. Consider the following code:

public class Person
    public string Name { get; set; }

If the app was built with enable, a missing value
for Name in a JSON or form post results in a validation error. Use a
nullable reference type to allow null or missing values to be
specified for the Name property:

public class Person
    public string? Name { get; set; }

This behavior can be disabled by configuring
SuppressImplicitRequiredAttributeForNonNullableReferenceTypes in

    options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

Leave a Reply Cancel reply