Reputation: 21
MVC6, There is issue found on model validation server side.
public string Genre { get; set; }
public decimal Price { get; set; }
If user submits decimal / int value empty from view, server side model validation shows wrong message i.e. the value "" is not valid.
I have checked in the controller, the incoming model is showing price value 0 as the default but ModelState getting rawValue="". So conflicting with datatype and throw msg.
model is carring 0 as default (even user submit with empty) so should validate with 0 not with "" (string.empty).
front javascript validation working fine but server side model validation shows wrong error message as "the value "" is not valid"
decimal / int is always getting 0 as default value.
Any solution to resolve this?
Upvotes: 2
Views: 1220
Reputation: 6203
I had similar problem in my ASP Core project. Model validation was set for integers by using Range
attribute and Required
with errors message. But when user put into input
control empty i get error message like
"The value '' is invalid."
In model value was 0 but raw value was empty. I have to edit my model for nullable properties and use attributes. And i get result as i want.
[Range(1, int.MaxValue,ErrorMessage = "My message1")]
[Required (ErrorMessage = "My message2")]
public int? PreparationTimeMinutes { get; set; }
I hope someone will help.
Upvotes: 1
Reputation: 141
you can add a validation region in your controller and validate it your self .
if (model.Price == 0)
ModelState.AddModelError("", "please enter the price .");
return View();
or if your ModelState.IsValid() is false you can tell the model state to prevent from validate that decimal/int field . Add this code before your ModelState.IsValid()
ModelState.Remove("Price");
then add the value 0 to it your self .
or if price is a required field you can add data annotations attributes to add customized validation errors to it :
[System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Please enter thye price .")]
public decimal price {get;set;}
Upvotes: 2