In my asp.net mvc 3 project I use [Required] attributes on properties that need to be validated. Also I use ModelState.AddModelError to add errors to the same properties (with attributes). The errors added with the second approach doesn’t show up. What could be the reason?
Here is the code:
1) property with attibute
[Required(ErrorMessage = "Product name is required")]
public string Name { get; set; }
2) in controller action method
if (p.Name.Length < 3)
ModelState.AddModelError("Name",
"Product name should be at least 3 characters long");
3) in the view
@Html.EditorFor(i => i.CurrentItem.Product.Name)
Html.ValidationMessageFor(i => i.CurrentItem.Product.Name)
@Html.ValidationMessage("Name")
So, mabby I can’t use attributes and ModelState both?
You can achieve the same thing by adding a
StringLengthattribute:Where
100is the max length and3the minimum length.