0
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 ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.