Home Ask Login Register

Developers Planet

Your answer is one click away!

Har February 2016

Data Annotation for MVC 5.0 is not working

public class DropDownListViewModel
    public string SelectedId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }

public class Account
    public DropDownListViewModel Country { get; set; }

How get error message related to Country field. Currently it shows generic message saying 'Selectedid is required', But I want message related to country field.


Tushar Gupta February 2016

Use ErrorMessage to have you own custom error message

[Required(ErrorMessage = "Custom Message")]
public string SelectedId { get; set; }

Ashley Medway February 2016

You can override the message in the view:

@Html.ValidationMessageFor(x => x.SelectedId, "You must select a country")

The downside to this is if you had multiple error for SelectedId only the overridden message will be displayed.

Post Status

Asked in February 2016
Viewed 3,156 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life