Use a DropDownList with a decimal in ASP.NET MVC3

2013 年 5 月 18 日4540

This code displays a drop down box with some options. The options are decimals. The user selects one, then presses save. On postback, the selected option should be chosen in the drop down box. This is not a problem with strings. This code is using decimals. When the postback comes back, nothing is selected. I think ASP.NET MVC is having trouble matching because of decimal precision.

The list of decimals to display in a drop down box

public static List<decimal> MyCustomFieldOptions



{



get



{



var x = new List<decimal>();



x.Add(0.10m);



x.Add(0.25m);







return x;



}



}



The property on the view model:

[UIHint("MyCustomField")]



public decimal MyCustomField { get; set; }



In the view:

@Html.EditorFor(model => model.MyCustomField)



EditorTemplate:

@model decimal







@Html.DropDownListFor(x => x, new SelectList(ProjectNamespace.MyViewModel.MyCustomFieldOptions), new {size="2"})



/Shared/EditorTemplates/MyCustomField.cshtml

This code properly displays a list box with two options to choose from. The user can select one, press save and the Controller gets the value. The controller will see either 0.25 or 0.1. However, when the page comes back, the item is no longer selected.

I'm pretty sure it's because of a decimal precision issue.

@Model.MyCustomField.ToString() returns 0.250.

Notice what the editor template outputs:

<select size="2">



<option>0.10</option>



<option>0.25</option>



</select>



The decimal precision of the options is different. 0.25, not 0.250 So it probably cannot match.

I read this SO article, which gave me the hint of creating the editor template and looking at the decimal precision.

0 0