Why is my dropdownlist not binding? Using the DropDownListFor Razor helper function.
View:
@Html.DropDownListFor(m => m.ModelObject.VatRate, Model.VatRatesList)
ViewModel:
public SelectList VatRatesList
{
get
{
return new SelectList(
new Dictionary<decimal, string>
{
{ 0m, string.Empty },
{ 1.2m, "20%" },
{ 1m, "0%" }
}, "Key", "Value",
ModelObject.VatRate ?? 0m);
}
}
Thanks.
UPDATE
On further investigation I have found out that this is something to do with the model property that I am trying to bind. It is a nullable decimal. When I change it to a decimal, the correct value is selected from the list.
Here is where things start to get weird. If I use 4 decimal places for the dictionary keys, it works with a nullable decimal model property. In other words, this works:
I have no idea why. Perhaps html helper uses ToString() internally. I think ToString() would give a 4dp string representation of the decimal. I’ll have to look at the MVC source code to find out.