0

Below is the Edit method from my controller. Everything works fine, however the current value for the agent in the FixedOrVariable drop down is not being set as the default value. I can edit this value properly, however.

The field FixedOrVariable is a one character field in the model. It's values are either F or V (always upper case).

Here is the controller method

    public ActionResult Edit(int id)
    {
        var banklistagentid = db.BankListAgentId.Find(id);
        ViewBag.BankID = new SelectList(db.BankListMaster, "ID", "BankName", banklistagentid.BankID);

        SelectList tmpList = new SelectList(new[] { "AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NA", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "US", "VT", "VI", "VA", "WA", "WV", "WI", "WY" });
        ViewBag.StateCodeList = tmpList;

        var fixedOrVariable = new[] {new {Text = "Fixed", Value = "F"}, new {Text = "Variable", Value = "V"}};
        ViewBag.FixedOrVariable = new SelectList(fixedOrVariable, "Value", "Text", banklistagentid.FixedOrVariable);

        return View(banklistagentid);
    }

And here is the code from the view

    <div class="editor-field">
        @Html.DropDownListFor(model => model.FixedOrVariable, (SelectList)ViewBag.FixedOrVariable)
    </div>
NealR
  • 10,189
  • 61
  • 159
  • 299
  • Please check few answers about the same question [here](http://stackoverflow.com/questions/781987/how-can-i-get-this-asp-net-mvc-selectlist-to-work/11705380#11705380). – ararog Apr 06 '13 at 18:33
  • Are your dropdown item display correctly? – Iswanto San Apr 06 '13 at 18:34
  • @ararog: There is no need to override the `ToString` method, should be a much easier solution. – NealR Apr 06 '13 at 18:39
  • @IswantoSan: Yes the dropdown items are displaying correctly. Everything works fine except the default value isn't loaded properly. – NealR Apr 06 '13 at 18:40

1 Answers1

1

This is probably the single biggest mistake I've seen people make with Dropdowns in MVC. You cannot name your list of choices the same as your selected item variable.

Change it to ViewBag.FixedOrVariableList

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291