1
遵循教程,並按照步驟進行,但在編輯字段時出現錯誤。具有鍵「JobTitleID」的ViewData項的類型爲「System.Int32」,但必須是「IEnumerable <SelectListItem>」類型的?
源錯誤:
</div>
<div class="editor-field">
@Html.DropDownList("JobTitleID", String.Empty)
@Html.ValidationMessageFor(model => model.JobTitleID)
</div>
這裏是我的控制器:
// POST: /Employee/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SIN, FirstName, MiddleName, LastName, StartDate, Salary, JobTitleID, DepartmentID")] Employee employee)
{
try
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException dex)
{
if (dex.InnerException.InnerException.Message.Contains("IX_Employee_SIN"))
{
ModelState.AddModelError("SIN", "Unable to save changes. Remember, you cannot have duplicate SIN numbers.");
}
else
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
}
DepartmentDropDownList(employee.DepartmentID);
JobDropDownList(employee.JobTitleID);
return View(employee);
}
//
// GET: /Employee/Edit/5
public ActionResult Edit(int id = 0)
{
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
DepartmentDropDownList(employee.DepartmentID);
JobDropDownList(employee.JobTitleID);
return View(employee);
}
//
// POST: /Employee/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID, SIN, FirstName, MiddleName, LastName, StartDate, Salary, JobTitleID, DepartmentID")] Employee employee)
{
try
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException dex)
{
if (dex.InnerException.InnerException.Message.Contains("IX_Employee_SIN"))
{
ModelState.AddModelError("SIN", "Unable to save changes. Remember, you cannot have duplicate SIN numbers.");
}
else
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
}
DepartmentDropDownList(employee.DepartmentID);
JobDropDownList(employee.JobTitleID);
return View(employee);
}
private void JobDropDownList(object selectedJob = null)
{
var dQuery = from d in db.JobTitles
orderby d.Title
select d;
ViewBag.JobID = new SelectList(dQuery, "ID", "Title", selectedJob);
}
private void DepartmentDropDownList(object selectedDepartment = null)
{
var dQuery = from d in db.Departments
orderby d.DepartmentName
select d;
ViewBag.DepartmentID = new SelectList(dQuery, "ID", "DepartmentName",selectedDepartment);
}
我真的不那麼熟悉MVC,只是認爲我會問這個問題是什麼,以及它如何被修復。
您正在使用哪個版本的MVC?它看起來像你試圖使用這種擴展方法:http://msdn.microsoft.com/en-us/library/dd504970(v=vs.108).aspx - 也許它是在一個晚於你正在使用的一個? –
我正在使用mvc 4 –
錯誤提示您試圖將一個整數綁定到期望IEnumerable選擇列表項的下拉列表中 – Adween