0

我正在尝试使用 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)
4

1 回答 1

1

这是因为在您的 HttpPost 控制器操作中,当您呈现相同的视图时,您忘记在视图模型上填充 Groups 属性:

RM.Groups = RM.InitializeGroupList();

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

于 2013-10-25T17:46:40.553 回答