0

I am getting my head round mvc forms, and trying to bind a DropDownList in mvc but get this error:

Value cannot be null.
Parameter name: items

On:

@Html.DropDownListFor(x => x.JobRoles, new SelectList(Model.JobRoles, "value", "text"))

My controller:

public ActionResult Create(ContactViewModel myViewData)
{
    List<SelectListItem> JobRoles_list = new List<SelectListItem>();
    JobRoles_list.Add(new SelectListItem
    {
        Text = "1",
        Value = "1"
    });
    // ViewBag.JobRoles = JobRoles_list;
    myViewData.JobRoles = JobRoles_list;
    return View(myViewData);
}

My model:

public class ContactViewModel
{
    public List<SelectListItem> JobRoles { get; set; }
}

My view:

@Html.DropDownListFor(x => x.JobRoles, new SelectList(Model.JobRoles, "value", "text"))
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
PeteTheGreek
  • 729
  • 2
  • 21
  • 41
  • Shouldn't be `Value` and `Text`? – Phiter Dec 04 '16 at 18:16
  • You cannot use the same name for the property your binding to and the name of the `SelectList`. And the error occurs in the POST method when you return the view because you did not repopulate the `SelectList. And do not include you model as a parameter in the GET method. Refer the answers [here](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557) and [here](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) –  Dec 04 '16 at 21:01
  • And your model needs a separate property to bid to (say) `public int SelectedRole { get; set; }` (a ` –  Dec 04 '16 at 21:12

0 Answers0