Search code examples
asp.net-mvcrazorhttp-postienumerabledropdownlistfor

MVC Razor - DropDownListFor - Error on Post


i'm trying to associate the selected Value to a a parameter defined in Model but now i have the error: "Value cannot be null. Parameter name: items"

In Model i have:

public class ObjectivesModel
{

    [Required(ErrorMessage = "*")]
    [Display(Name = "AssociatedGoal")]
    public int AssociatedGoal { get; set; }

}

In Controler i create the list

[HttpGet]
    public ActionResult NewObjective()
    {
        IEnumerable<SelectListItem> example = new List<SelectListItem>
        {
            new SelectListItem() { Text = "ola1", Value = "1" },
            new SelectListItem() { Text = "ola2", Value = "2" }
        };

        ViewBag.GoalsToAssociate = example;

        return View();
    }

And Finally in View I have

@using (Html.BeginForm()){

             <div class="editor-label">@Html.LabelFor(o => o.AssociatedGoal)</div>
            <div class="editor-DropDownList">@Html.DropDownListFor(o => o.AssociatedGoal, new SelectList(@ViewBag.GoalsToAssociate, "Value", "Text"), "--Select Goal--")
            @Html.ValidationMessageFor(o => o.AssociatedGoal)

            </div>

So the error occurs when i submit the form.. I have any special code yet on post version of controler

[HttpPost]
    public ActionResult NewObjective(Models.ObjectivesModel objective)
    {

        return View();
    }

Solution

  • You say that you get this error while posting this form. Maybe you don't pass the SelectList to the View in your [HttpPost] version of the Action?

    Edit:

    In response to your edit: You should also include the SelectList code in the [HttpPost] version.