user1618587
user1618587

Reputation: 45

Required attribute not displaying

Public Class Duration 
{
  [Required]
  Public DurationUnit Unit
  [Required]
  Public int Length
}

Public Class Employee
{
  [RequiredAttribute]
  public virtual Duration NotificationLeadTime { get; set; }
}

The fields Unit and Length, when not suplied are getting highlighted in Red but the error message is not getting displayed.

I tries also giving [Required(ErrorMessage="sadfdsf")],but this is also not working. I also tried inheriting the class with IValidatableObject but that also didn't work.

How to display the error message ?

Upvotes: 0

Views: 134

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You should use properties, not fields:

public class Duration 
{
    [Required]
    public DurationUnit Unit { get; set; }

    [Required]
    public int Length { get; set; }
}

In order to display the corresponding error message use the Html.ValidationMessageFor helper.

For example:

@Html.EditorFor(x => x.NotificationLeadTime.Unit)
@Html.ValidationMessageFor(x => x.NotificationLeadTime.Unit)

By the way it doesn't really make sense to decorate a non-nullable type such as int with the [Required] attribute because those types always have a default value. You should make it a nullable integer instead. Same remark stands for the DurationUnit property if DurationUnit is an enum.

Upvotes: 3

Related Questions