这是我的问题:
我正在研究MVC互联网应用程序,并尝试管理用户。首先,我的编辑视图显示所选用户的用户名和角色。可以选择用户的角色在我的HTML视图中的DropDownListFor中列出。当我点击“编辑此用户”时,出现错误:
具有键«RoleId»的ViewData元素是«System.Int32»类型,但需要和«IEnumerable»。
以下是我的观点型号:
using GestionStages.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc; >
> namespace GestionStages.Areas.Stages.ViewModels
{
public class UserRoleViewModel
{
public RegisterModel Register { get; set; }
public SelectList Roles { get; set; }
public UserProfile User { get; set; }
public String CurrentUserName { get; set; }
[Required(ErrorMessage = "A role is required")]
public int RoleId { get; set; }
}
}
以下是我的HTML编辑视图的一部分:
<div class="form_row">
@Html.Label("Roles")
@Html.DropDownListFor(x => x.RoleId, Model.Roles)
</div>
以下是我的控制器中的编辑方法:
public ActionResult Edit(int id = 0)
{
UserRoleViewModel model = new UserRoleViewModel();
model.User = db.UserProfiles.Find(id);
if (model.User == null)
{
return HttpNotFound();
}
model.Roles = new SelectList(db.webpages_Roles.ToList(), "RoleId", "RoleName");
model.CurrentUserName = model.User.UserName;
model.RoleId = model.User.webpages_Roles.FirstOrDefault().RoleId;
return View(model);
}
//
// POST: /Sales/Sale/Edit/5
[HttpPost]
public ActionResult Edit(UserRoleViewModel model)
{
if ((model.User.UserName != model.CurrentUserName && db.UserProfiles.Where(x => x.UserName == model.User.UserName).Any()))
{
ModelState.AddModelError("", "The user is already in the database");
}
if (ModelState.IsValid)
{
db.Entry(model.User).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
感谢您的帮助