I am currently trying to combine the Html Helper functions DropDownListFor
and ValidationMessageFor
. I am using asp.Net MVC 5 and have generated a model. My goal is to have an HTML select-box, which is generated by the function DropDownListFor
. This should be linked to my model. It is assumed that the client enters something into the field in the frontend in the select-box. If the client doesn't enter anything and clicks on the submit button of my form, the ValidationMessageFor
function should be used to display the error text I entered in the model. Of course the form shouldn't be valid and the client shouldn't be allowed to continue as long as nothing is selected in the select-box. That's the theory.
As already mentioned, I have created a model. It looks like this:
public class ExampleModel
{
[Required(ErrorMessage="Test-Error-Text")]
public string salutation { get; set; }
}
I set the values in the select-box in the controller as follows:
var collection = new ListItemCollection();
collection.Add(new ListItem("Mr"));
collection.Add(new ListItem("Mrs"));
collection.Add(new ListItem("unknown"));
collection.Add(new ListItem("company"));
var selList = new SelectList(collection, "Salutation");
ViewBag.Salutation = selList;
Then I call the functions in the view as follows:
@Html.DropDownListFor(Model=> Model.salutation, ViewBag.Salutation as SelectList, "", new { @class="adrInput form-control"})
@Html.ValidationMessageFor(Model=>Model.salutation)
As this is currently, I get the following exception when submitting:
System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'salutation'.'
I have almost never worked with these Html Helper functions. Something is wrong here. I'm grateful for any help.
I found the mistake. I have to return the model to the view after submitting the form, if the form is not valid. Furthermore I have to initialize the SelectList for the ViewBag again. Somehow the values get lost in ViewBag.Salutation after validation.