Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC4 Code First - Data validation doesn't work

I have problem with data validation in forms. I declare error messages in model but it seems that it doesn't have any effect in the View. I have the following model:

public class Dog
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Id")]
    public int Id { get; set; }

    [Display(Name = "Name")]
    [StringLength(20)]
    public string Name { get; set; }

    [Display(Name = "Value")]
    [Range(1, int.MaxValue, ErrorMessage="Minimum value is 1")]
    public int Value { get; set; }
}

And in View I have this:

<div class="editor-field">
@Html.EditorFor(model => model.Value)
@Html.ValidationMessageFor(model => model.Value)
</div>

The problem is that there is no error message when user chooses to enter number which is lower than 1 as you can see here:

enter image description here

What am I missing here? Thank you for your help.

like image 212
Cristiano Avatar asked Mar 24 '26 23:03

Cristiano


1 Answers

Judging by the no tags, no references or any mentions of jQuery validation, we can safely see you're trying to validate the good old fashioned way (the out of the box way).

You have to invoke the validation yourself in your post method, by calling ModelState.IsValid. If that fails, the error messages will show on the erroneous fields. You'd had something like this:

[HttpPost]
public ActionResult Edit (Dog model)
{
    if (ModelState.IsValid)
    {
        //He's a good dog, save him, then redirect elsewhere
    }
    else
    {
        //He's a bad dog, return the same view and the errors are shown
        return View(model);
    }
}
like image 104
mattytommo Avatar answered Mar 26 '26 13:03

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!