我正在使用Visual Studio 2012.这是BikeController和Bike Model。当我运行程序时,错误是“无法使用集合初始化程序初始化类型'MvcApplication3.Models.Bike',因为它没有实现'System.Collections.IEnumerable'。”错误在行bikes = new Bike {
上但是当我在自行车模型中放置using System.Collections.IEnumerable;
时,它说“使用命名空间指令只能应用于命名空间;'System.Collections.IEnumerable'是一个类型而不是命名空间。“提前谢谢。
自行车控制器:
using MvcApplication3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
public class BikeController : Controller
{
//
// GET: /Bike/
Bike bikes;
public BikeController()
{
bikes = new Bike {
new Bike(),
new Bike { Manufacturer = "Nishiki", Gears = 5, Frame = "Road" }
};
}
public ActionResult Index()
{
return View(this.bikes);
}
private ActionResult View(Func<object> func)
{
throw new NotImplementedException();
}
//
// GET: /Bike/Details/5
public ActionResult Details(Bike b)
{
return View(b);
}
//
// GET: /Bike/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Bike/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Bike/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Bike/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Bike/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Bike/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
自行车模型:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MvcApplication3.Models
{
public class Bike
{
public int BikeID { get; set; }
public string Manufacturer { get; set; }
public int Gears { get; set; }
public string Frame { get; set; }
static protected int bikeCount;
public Bike()
{
this.Manufacturer = "Schwinn";
this.Gears = 10;
this.Frame = "Mountain";
this.BikeID = bikeCount;
bikeCount++;
}
}
}
答案 0 :(得分:1)
将变量自行车声明为列表
List<Bike> bikes;
然后实例化它
bikes = new List<Bike>() {
new Bike(),
new Bike() { ... },
...
};
答案 1 :(得分:0)
像这样初始化控制器:
public class BikeController : Controller
{
//
// GET: /Bike/
List<Bike> bikes;
public BikeController()
{
bikes = new List<Bike>() {
new Bike(),
new Bike { Manufacturer = "Nishiki", Gears = 5, Frame = "Road" }
};
}
...
}
答案 2 :(得分:0)
你必须使用List&lt;&gt;对于自行车。