开发者

Model binding problem with DropDownListFor

开发者 https://www.devze.com 2023-03-29 06:16 出处:网络
@Html.DropDownListFor(model => model.Activity.ActivityType, new SelectList(Model.ActivityTypes, \"ActivityTypeId\", \"Name\") )
@Html.DropDownListFor(model => model.Activity.ActivityType, new 
     SelectList(Model.ActivityTypes, "ActivityTypeId", "Name") )

I've got the above dro开发者_如何学Gopdownlist 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


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")
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号