I have a view where I load a form to update a user. When I populate my view model UpdateUserViewModel
with data to show on the page, the Info
property on UserModel
is null. This is expected because there simply isn't a record for it in the database, so it is not retrieved. However, I still add hidden fields for its two properties because when I post the form, I want the Info
property to be created with default values, which does happen.
public UpdateUserViewModel {
public UserModel User { get; set; }
}
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
public InfoModel Info { get; set; }
}
public class InfoModel {
public DateTime InfoDate { get; set; }
public string ConcurrencyToken { get; set; }
}
Posting the form results in ModelState.IsValid
to be false for the InfoDate
property on the InfoModel
. It gives the error message The value '' is invalid
. But this does not make sense because when I inspect the posted model's InfoDate
value, I see it is the default min date 1/1/0001 12:00:00 AM
.
I've thought about making the InfoDate
nullable, but that doesn't make sense because I'm required to map this property onto a business layer model and set it to the default date anyway. I also don't understand why it's showing that error when it clearly defaults to a value.
Why am I getting The value '' is invalid
when I see that the empty date the form submitted has successfully defaulted to 1/1/0001 12:00:00 AM
? How can I fix this?
I'm thinking maybe it's looking specifically at what value the user had set it to in the field instead of what ends up as the value of the property? But if so, why would it care? I don't have any validation attribute on InfoDate
, such as [Required]
.
CodePudding user response:
When binding data in client side,it will get value from ModelState prior to Model .Try to add ModelState.Clear()
and TryValidateModel(xxx)
before you check the ModelState.And then you will not get The value '' is invalid
.
ModelState.Clear();
TryValidateModel(MyProperty);
var IsValid=ModelState.IsValid;