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