Michael
Michael

Reputation: 91

Model binding problem with DropDownListFor

@Html.DropDownListFor(model => model.Activity.ActivityType, new 
     SelectList(Model.ActivityTypes, "ActivityTypeId", "Name") )

I've got the above dropdownlist in my view. On submission on my form the selected ActivityType isn't able to bind to the Model.Activity.ActivityType property in my model.

There is an error saying unable to convert string to ActivityType.

I assume this is because it is just trying to bind the Name property of the ActivityType rather than the entire object.

What do I need to do to ensure that on submission of the form the selected ActivityType is correctly bound to the model?

Thank you

Upvotes: 0

Views: 2181

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

The property used in the lambda as first argument to the DropDownListFor helper must be a scalar value (string, integer, ...). You should not use complex types as a <select> element in an HTML form submits only a single value. So you might need to bind to the corresponding id property:

@Html.DropDownListFor(
    model => model.Activity.ActivityType.ActivityTypeId, 
    new SelectList(Model.ActivityTypes, "ActivityTypeId", "Name")
)

Upvotes: 6

Related Questions