Reputation: 18650
Hi I have a MVC application with a dropdownlist in the view:
<div class="editor-label">
@Html.LabelFor(model => model.CompanyId)
</div>
<div class="editor-field">
@Html.DropDownList("CompanyId", "--- Select ---")
@Html.ValidationMessageFor(model => model.CompanyId)
</div>
In the model I have:
[Required(ErrorMessage = "Company is a required field.")]
[Display(Name = "Company:")]
public int CompanyId{ get; set; }
In the Controller for the Create Get Method I have:
ViewBag.CompanyId= new SelectList(_repository.GetAll<Company>(), "Id", "Name");
So originally the editor was a standard textbox and the validation worked fine. Now I've changed it to the dropdownlist everything works fine except for the validation. So on the HTTP POST Create if you don't select anything from the dropdownlist the ModelState.IsValid
is false which is correct.
The problem is with the dropdownlist the Validation Messages no longer appear for this field like they did when it was a textbox. I understand I probably have the ValidationMessageFor incorrect.
Can somebody please tell me how to get this working?
Upvotes: 2
Views: 6400
Reputation: 787
Is there a particular reason you are using the Html.DropDownList rather thatn the Html.DropDownListFor?
Let me give you an example on how I have done it in the past, it may or may not help you.
@Html.DropDownListFor(model => model.Vendor.State, new SelectList(Model.StatesList, "State1", "State1"), new { @class = "textboxSmall" })<br />
@Html.ValidationMessageFor(model => model.Vendor.State)
The state list is a property collection in my view model that I use to populate the dropdown list with.
public List<State> StatesList
{
get
{
StatesCollection st = new StatesCollection();
st.LoadStatesList();
return st.StatesList;
}
}
Upvotes: 2