2

In my ASP.NET MVC4 model I have a required property:

[Required(ErrorMessage = "Select a class")]
public string ClassName { get; set; }

This is bound to a drop-down list in the Razor view:

@Html.DropDownListFor(o => o.ClassName, new SelectList(Model.ClassList))
@Html.ValidationMessageFor(model => model.ClassName)

However, I have set the first element of Model.ClassList as the placeholder string "Select one". If the user submits the form without choosing a class, it registers as valid because ClassName has a value of "Select one".

How can I make this placeholder selection invalid?

2
  • 1
    You could remove the placeholder from the Model property and put it in the helper: @Html.DropDownListFor(o => o.ClassName, new SelectList(Model.ClassList), "Select one") Commented Feb 12, 2013 at 21:43
  • @Forty-Two Thanks, that's worked! I didn't notice that helper overload. Please add this as an answer and I'll accept it. Commented Feb 12, 2013 at 22:05

1 Answer 1

5

You could remove the placeholder from the Model property and put it in the helper:

@Html.DropDownListFor(o => o.ClassName, new SelectList(Model.ClassList), "Select one") 
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.