Environment: Entity Framework (v6.0) with MVC and Razor. Backend is SQL Server.
HTML helper DropDownListFor() is working perfectly for a string column on the database. However, when I use a decimal column with a numeric dropdownlist the framework does not select the value loaded from the database when the form is rendered.
I assume this is related to the fact that DropDownListFor() contains strings for both Text and Value, and cannot match the decimal value from the database, so SelectedItem is not determined.
I've tried casting within the HTML helper, but fails either at compile or runtime. All examples I can find assume you want to select a string, not a number.
Any help gratefully received. Thanks.
View code: the problem field is CollarSize. The dropdownlist is CollarSizeSelect.
<div class="form-group">
@Html.LabelFor(model => model.CollarSize, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CollarSize, Model.CollarSizeSelect, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CollarSize, "", new { @class = "text-danger" })
</div>
</div>
The class definition contains the column defined thus:
public Nullable<decimal> CollarSize { get; set; }
CollarSize dropdown list is built as follows:
public IEnumerable<SelectListItem> ChestSizeSelect
{
get
{
return GetSelectNumberRange(32, 60, (decimal)1.0);
}
}
private static List<SelectListItem> GetSelectNumberRange(int start, int end, decimal increment)
{
List<SelectListItem> numlist = new List<SelectListItem>();
for (decimal i = start; i <= end; i = i + increment)
{
numlist.Add(new SelectListItem() {Text = i.ToString(), Value = i.ToString()});
}
return numlist;
}
decimal
in html. If the value ofCollarSize
matches exactly the value of one of your options (i.e. usingToString()
) then that option will be displayed – user3559349@Html.DropDownListFor(model => model.CollarSize.ToString(),
– S JonesCollarSize
. If its (say)42
and you have an option withvalue="42"
then it will be selected. Does the value ofCollarSize
match exactly the value of one of your options – user3559349CollarSize.ToString()
is not returning"15.0"
– user3559349