Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Razor - All form fields are required?

I have a form that is generated by ASP.NET. I have some required fields, and I am using the [Required] dataAnnotation for that. However, the elements that don't have the [Required] DataAnnotation are also required according to my webpage. These are not required at all yet I cannot submit the form if they are empty.

I used scaffolding to make the pages, jquery validator is used (by default) for the validation.

Model class (some fields have been omitted for clarity)

public class Room
{
    [Key]
    public int ID { get; set; }


    [Required(ErrorMessage = "Please enter the minimum (default) price for this room.")]
    [DataType(DataType.Currency)]
    [Display(Name = "Minimum price")]
    public decimal MinPrice { get; set; }

    [Display(Name = "Alternative price")]
    [DataType(DataType.Currency)]
    public decimal AltPrice { get; set; }
}

The code that creates the form fields in de .cshtml file:

    <div class="form-group">
        @Html.LabelFor(model => model.MinPrice, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.MinPrice)
            @Html.ValidationMessageFor(model => model.MinPrice)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.AltPrice, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.AltPrice)
            @Html.ValidationMessageFor(model => model.AltPrice)
        </div>
    </div>

The required field correctly displays the error message as defined (thus it reads the annotations). The non required field displays a generic error message instead ("The Alternative price field is required.").

I've searched quite a lot, but everywhere it says that if the [Required] DataAnnotation is not there, it won't be required in the form.

like image 392
Chirimorin Avatar asked Apr 06 '14 08:04

Chirimorin


2 Answers

Make the non-required fields nullable.

like image 58
Martin Costello Avatar answered Oct 03 '22 02:10

Martin Costello


I was having the same problem. I had to go into my model and put ? marks in the int fields to make them null. The fields that were set as string were fine it was just the int fields that were causing the issue.

like image 42
ctm1988 Avatar answered Oct 03 '22 02:10

ctm1988