在MVC中使用dropdownlistfor的问题

时间:2013-10-25 17:44:17

标签: asp.net-mvc asp.net-mvc-4 html.dropdownlistfor

我正在尝试使用MVC4提交表单,似乎无法弄清楚为什么在提交后会出现错误。我已粘贴下面的所有相关代码以及我看到的错误。

错误:

The ViewData item that has the key 'Group' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.

控制器:

[HttpGet]
public ActionResult CreateRole()
{
var RM = new myModel();
RM.Groups = RM.InitializeGroupList();
return View(RM);
}

[HttpPost]
public ActionResult Myfunction(myModel model)

if (ModelState.IsValid)
{
//Execute Update
}

型号:

[Required]
[Display(Name = "Group")]
public string Group { get; set; }


public IEnumerable<SelectListItem> Groups;  

public IEnumerable<SelectListItem> InitializeGroupList()
    {
        List<SelectListItem> topOfList = new List<SelectListItem>
        {
            new SelectListItem { Value = string.Empty, Text = "Category" },
            new SelectListItem { Value = "Administrator", Text = "Administrator" },
            new SelectListItem { Value = "Partner", Text = "Partner" },
            new SelectListItem { Value = "Internal", Text = "Internal" }
        };
        //IEnumerable<SelectListItem> list = db.GetRoleList(topOfList);
        IEnumerable<SelectListItem> list = topOfList;
        return new SelectList(list, "Value", "Text");
    }

[Required]
[Display(Name = "Group")]
public string Group { get; set; }


public IEnumerable<SelectListItem> Groups;

查看:

    @Html.DropDownListFor(model => model.Group, Model.Groups)

1 个答案:

答案 0 :(得分:1)

那是因为在您的HttpPost控制器操作中,在渲染相同视图的情况下,您忘记在视图模型上填充Groups属性:

RM.Groups = RM.InitializeGroupList();

不要忘记DropDownList在您提交表单时仅发送选定的值。如果您打算重新显示相同的视图,则其他值取决于您在GET操作中检索的方式。