我从内存数据填充DropDownList并在POST上获取此错误。具有'位置'键的ViewData项的类型为'System.String',但必须是'IEnumerable <SelectListItem>'的类型'
具有'位置'键的ViewData项的类型是'System.String',但必须是'IEnumerable'类型。
型号:
public class StaffModel
{
public int id { get; set; }
public string Email { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string PasswordConfirm { get; set; }
public string Emp_Name { get; set; }
public string Emp_Address { get; set; }
public string Phone { get; set; }
public string Position { get; set; }
public List<SelectListItem> Positions { set; get; }
}
控制器:
public ActionResult Register()
{
IEnumerable<SelectListItem> position = db.Positions.Select(p => new SelectListItem
{
Text = p.Position_Title,
Value = p.Position_ID.ToString()
});
ViewBag.Position = position;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(StaffModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
Employee em = new Employee
{
Employee_Name = model.Emp_Name,
Address = model.Emp_Address,
Phone = model.Phone,
Position_ID = Convert.ToInt32(db.Positions.Where(p => p.Position_Title == model.Position).Select(p => p.Position_ID)),
};
db.Employees.Add(em);
db.SaveChanges();
return RedirectToAction("Index", "Employees");
}
}
return View(model);
}
enter code here
HTML /剃刀:
<div class="form-group">
@Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Position",null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Position, "", new { @class = "text-danger" })
</div>
</div>
我道歉,我重读这发生在后期..你必须在'HttpGet'和'HttpPost'行为方法中声明'ViewBag.Position',很可能在你的'if'语句之上 –
我也对你的.Where语句感到困惑..'p.Position_Title'不应该等于'model.Position',因为'model.Position'将是下拉列表的**值** ..不是文本..所以基本上你的意思是'.Where(p => p.Position_Title == p.Position_ID.ToString())' –
@BviLLe_Kid我该如何解决它? – bao4461826