我從內存數據填充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