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

Time:09-15

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:

    <div>
        <label asp-for="FirstName"></label>
        <input asp-for="FirstName" />
        <span asp-validation-for="FirstName" ></span>
    </div>
    <br />
     <div>
        <label asp-for="LastName"></label>
        <input asp-for="LastName"  />
        <span asp-validation-for="LastName" ></span>
    </div>
    <div>.......

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.

CodePudding user response:

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 Program.cs:

builder.Services.AddControllers(
    options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  • Related