Mvc SelectList does not bind if dictionary key can be decimal

Why is my dropdownlist optional? 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);
        }
    }

Thank.

+3
source share
2 answers

UPDATE

In the course of further research, it turned out that this is due to the property of the model that I am trying to relate. This is a number with a zero value. When I change it to decimal, the correct value is selected from the list.

That's where things start to get weird. If I use 4 decimal places for dictionary keys, it works with a zero value of the decimal model. In other words, this works:

 public SelectList VatRatesList
    {
        get
        {
            return new SelectList(
                new Dictionary<decimal, string>
                {
                    { 0.0000m, string.Empty },
                    { 1.2000m, "20%"},
                    { 1.0000m, "0%"}
                }, "Key", "Value");
        }
    }

, . , html helper ToString() . , ToString() . MVC, .

+3

( /, ). , :

:

 public ActionResult Index()
 {
        var model = new Model();
        model.ModelObject = new ModelObject();

        model.ModelObject.VatRatesList = new SelectList(
            new Dictionary<decimal, string>
            {
                { 0m, string.Empty },
                { 1.2m, "20%" },
                { 1m, "0%" }
            }, "Key", "Value",
            model.ModelObject.VatRate ?? 0m);

        return View(model);
 }

:

@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.ModelObject.VatRate, Model.ModelObject.VatRatesList)
<input type="submit" value="Submit me"/>
}

:

[HttpPost]
public ActionResult Index(Model model)
{
    //Breakpointing on the below line, I can see model.ModelObject.VatRate
    return RedirectToAction("Index");
}

:

public class Model
{
    public ModelObject ModelObject { get; set; }
}

public class ModelObject
{
    public decimal? VatRate { get; set; }
    public SelectList VatRatesList { get; set; }
}
+1

All Articles