5.9 KiB
sidebar_position | title |
---|---|
5 | Creation of the add model |
Add model
In order to add an element we will create an object representing our item.
For this in create a new class Models/ItemModel.cs
, this class will include all the information of our API object.
We will also add a property so that the user accepts the conditions of addition.
Similarly, annotations will be present to validate the fields of our forms.
public class ItemModel
{
public int Id { get; set; }
[Required]
[StringLength(50, ErrorMessage = "The display name must not exceed 50 characters.")]
public string DisplayName { get; set; }
[Required]
[StringLength(50, ErrorMessage = "The name must not exceed 50 characters.")]
[RegularExpression(@"^[a-z''-'\s]{1,40}$", ErrorMessage = "Only lowercase characters are accepted.")]
public string Name { get; set; }
[Required]
[Range(1, 64)]
public int StackSize { get; set; }
[Required]
[Range(1, 125)]
public int MaxDurability { get; set; }
public List<string> EnchantCategories { get; set; }
public List<string> RepairWith { get; set; }
[Required]
[Range(typeof(bool), "true", "true", ErrorMessage = "You must agree to the terms.")]
public bool AcceptCondition { get; set; }
[Required(ErrorMessage = "The image of the item is mandatory!")]
public byte[] ImageContent { get; set; }
}
Concept: Data Annotation
Validation attributes
Validation attributes allow you to specify validation rules for model properties.
The following example shows a model class that is annotated with validation attributes.
The [ClassicMovie]
attribute is a custom validation attribute, and the others are predefined.
public class Movie
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
[ClassicMovie(1960)]
[DataType(DataType.Date)]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
[Required]
[StringLength(1000)]
public string Description { get; set; }
[Range(0, 999.99)]
public decimal Price { get; set; }
public Genre Genre { get; set; }
public bool Preorder { get; set; }
}
Attributs prédéfinis
Here are some of the predefined validation attributes:
[ValidateNever]
: ValidateNeverAttribute Indicates that a property or parameter should be excluded from validation.[CreditCard]
: Checks that the property has a credit card format. Requires additional jQuery validation methods.[Compare]
: Validates that two properties of a model match.[EmailAddress]
: Checks that the property has an email format.[Phone]
: Checks that the property has a phone number format.[Range]
: Checks that the property value is within a specified range.[RegularExpression]
: Validates that the property value matches a specified regular expression.[Required]
: Checks that the field is not null. For more information on the behavior of this attribute, see [Required] attribute.[StringLength]
: Validates that a property value of type String does not exceed a specified length limit.[Url]
: Checks that the property has a URL format.[Remote]
: Validates input on the client by calling an action method on the server. For more information on the behavior of this attribute, see [Remote] attribute.
You can find the full list of validation attributes in the System.ComponentModel.DataAnnotations namespace.
Error Messages
Validation attributes allow you to specify the error message to display for invalid input. For instance :
[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]
Internally the attributes call String.Format
with a placeholder for the field name and sometimes other placeholders. For instance :
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
Applied to a Name
property, the error message created by the previous code would be "Name length must be between 6 and 8".
To find out what parameters are passed to String.Format
for the error message of a particular attribute, see the [DataAnnotations source code](https://github.com/dotnet/runtime/tree/main/src /libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations).
Custom attributes
For scenarios not handled by the predefined validation attributes, you can create custom validation attributes. Create a class that inherits from ValidationAttribute and override the IsValid method.
The IsValid
method accepts an object named value, which is the input to validate. An overload also accepts a ValidationContext
object, which provides additional information such as the model instance created by the model binding.
The following example checks that the release date of a movie belonging to the Classic genre is not later than a specified year. The [ClassicMovie]
attribute:
- Runs only on the server.
- For classic films, validate the publication date:
public class ClassicMovieAttribute : ValidationAttribute
{
public ClassicMovieAttribute(int year)
{
Year = year;
}
public int Year { get; }
public string GetErrorMessage() =>
$"Classic movies must have a release year no later than {Year}.";
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var movie = (Movie)validationContext.ObjectInstance;
var releaseYear = ((DateTime)value).Year;
if (movie.Genre == Genre.Classic && releaseYear > Year)
{
return new ValidationResult(GetErrorMessage());
}
return ValidationResult.Success;
}
}
The movie
variable in the previous example represents a Movie
object that contains the form submission data. When validation fails, a ValidationResult
with an error message is returned.