ASP.NET MVC DropDownListFor not selecting value from model

后端 未结 5 691
梦毁少年i
梦毁少年i 2020-11-30 09:11

I\'m using ASP.NET MVC 3, and just ran into a \'gotcha\' using the DropDownListFor HTML Helper.

I do this in my Controller:

ViewBag.Ship         


        
5条回答
  •  情歌与酒
    2020-11-30 09:43

    The reason why this doesn't work is because of a limitation of the DropDownListFor helper: it is able to infer the selected value using the lambda expression passed as first argument only if this lambda expression is a simple property access expression. For example this doesn't work with array indexer access expressions which is your case because of the editor template.

    You basically have (excluding the editor template):

    @Html.DropDownListFor(
        m => m.ShippingTypes[i].RequiredShippingTypeId, 
        ViewBag.ShippingTypes as IEnumerable
    )
    

    The following is not supported: m => m.ShippingTypes[i].RequiredShippingTypeId. It works only with simple property access expressions but not with indexed collection access.

    The workaround you have found is the correct way to solve this problem, by explicitly passing the selected value when building the SelectList.

提交回复
热议问题