I have the situation that is the Notes column inside of the table is NULL. This data is imported automatically.
I have page where user open to edit that record including the Notes field, but the Notes field is required value when user submits the form. I know the validation for Notes field can be down at the client-side using Javascript, but I like validate using MVC Data Annotations if possible.
Here is the Model (simplified)
public class DetailModel
{
// Some other properties here....
public string? Notes { get; set; }
}
From the Controller, it call the method below and the edit page works fine.
public async Task<DetailModel?> GetDetail(string? id)
{
List<DetailModel> Info = await _context.Database.SqlQuery<DetailModel>($@"EXECUTE [dbo].[p_DetailView] @Method = 'Info', @RecID = {id}").ToListAsync();
return Info.FirstOrDefault();
}
Now if I try to validate using Data Annotations like below, it will break
public class DetailModel
{
// Some other properties here....
[Required]
public string? Notes { get; set; }
}
Error Message:
*SqlNullValueException: Data is Null. This method or property cannot be called on Null values. Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()
InvalidOperationException: An error occurred while reading a database value for property 'DetailModel.Notes'. The expected type was 'System.String' but the actual value was null.*
Is there a way to overcome this? Given the initial data is NULL, but enforce on the form submit to require value using Data Annotations.