MVC Razor - DropDownListFor - 帖子出错

时间:2013-05-29 14:57:35

标签: asp.net-mvc razor http-post ienumerable dropdownlistfor

我正在尝试将所选值与模型中定义的参数相关联,但现在我有错误:“值不能为空。 参数名称:items“

在模型中我有:

public class ObjectivesModel
{

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

}

在Controler中,我创建了列表

[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();
    }

最后在视图中我有

@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>

因此,当我提交表单时发生错误.. 我在控制器的后期版本上有任何特殊代码

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

        return View();
    }

1 个答案:

答案 0 :(得分:0)

您说在发布此表单时收到此错误。也许您没有将SelectList传递给View[HttpPost]中的Action

修改

响应您的修改:您还应该在SelectList版本中加入[HttpPost]代码。