2
你好我所有我是新來的MVC,我無法找到以下例外的解決方案。異常「沒有ViewData項的類型'IEnumerable <SelectListItem>」MVC
「沒有類型爲」IEnumerable「的ViewData項具有」部門「關鍵字。」
這裏是它
@using LearningMVCDAL
@using LearningMVCDAL.Classes
@model Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.DropDownList("Gender", new List<SelectListItem>{
new SelectListItem { Text="Male", Value="Male"},
new SelectListItem { Text="Female", Value="Female"}},"Select Gender")
@Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<div class="editor-label">
@Html.Label("Department")
</div>
<div class="editor-field">
@Html.DropDownList("Department", (IEnumerable<SelectListItem>)ViewBag.Departments,"Select Department")
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
控制器代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LearningMVCBLL;
using LearningMVCDAL;
using LearningMVCDAL.Classes;
namespace LearningMVC.Controllers
{
public class EmployeeController : Controller
{
#region ObjectDeclartions
EmployeeBusinessLayer objEmployeeBusinessLayer = new EmployeeBusinessLayer();
DepartmentBusinessLayer objDepartmentBusinessLayer = new DepartmentBusinessLayer();
#endregion
public ActionResult Index()
{
List<Employee> employees = objEmployeeBusinessLayer.Employee;
return View(employees);
}
[HttpGet]
public ActionResult Create()
{
List<Department> departments = new List<Department>();
departments = objDepartmentBusinessLayer.Department;
SelectList departmentList = new SelectList(departments, "ID", "Name");
ViewBag.Departments = departmentList;
return View();
}
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
if (ModelState.IsValid)
{
foreach (string key in formCollection.AllKeys)
{
Response.Write("Key = " + key + " ");
Response.Write("Value = " + formCollection[key]);
Response.Write("<br/>");
}
}
return View();
}
}
}
我改變,但仍然得到了同樣的錯誤CSHTML代碼。我在發佈數據「HttpPost」創建函數時發生此錯誤。 在此先感謝。
感謝林。你拯救了我的一天。你能指導我一本好書或一系列教程,從我可以學習這個MVC的東西。 –
我個人喜歡在這裏學習asp.net MVC:http://www.asp.net/,但是如果你想看書選項,我推薦這本書:http://www.amazon.com/Pro- ASP-NET-MVC-Adam-Freeman/dp/1430242361 – Lin
謝謝你,我總是在發佈'null',但是這對我有幫助。 – stom