DropDownListFor with an item value 0 always selected

允我心安 提交于 2019-12-01 08:28:49

I would look at what the type of the model.Rating property is, I am assuming it is an int. If this is an (int) type and you are not providing a value, it will be bound to a 0 when it comes across to a view. As such, when the view is processed, 0 will be marked as selected, that is what the view engine thinks the right value is and will override the selected value that you manually chose. Try making the model.Rating property a nullable int (int?) and see if you have the same issues.

Secondly, you could always look into a quick jQuery function to reset the drop-down to the first provided value, but that might be a little more "hacky" than what you are looking for.

The solution is to either avoid an item having 0 as value because Rating is an int (with default value equal 0), or, handle binding of DropdownList yourself by using Html.DropDownList instead. If you choose latter, you also have to specify Selected for the item user has selected while binding it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!