我正在学习 MVC 和 Entity Framework ,所以请回答我的问题...我正在尝试为我的模型类 SinglePest 创建一个属性(枚举类型)的下拉菜单 这是模型:
public class SinglePest
{
public int SinglePestId { get; set; }
public PestType PestType { get; set; } // here is my problem
public string Alias { get; set; }
public string TechName { get; set; }
public string Markings { get; set; }
public string SerialNumber { get; set; }
public SourceType SourceType { get; set; }
//virtual property
public Source Source { get; set; }
}
这是 PestType:
public enum PestType
{
Dog,
Cat,
Fox,
Rabbit,
Rat
}
这是 Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create (//(SinglePest singlepest)
[Bind(Include= "Alias, TechName, SerialNumber, PestType, Markings")] SinglePest singlepest)
{
try
{
if (ModelState.IsValid)
{
db.SinglePests.Add(singlepest);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
ModelState.AddModelError("", "Unable to save changes, try again, if problem persits contact your administrator");
}
//ViewBag.SerialNumber = new SelectList(db.Sources, "SerialNumber", "SerialNumber", singlepest.SerialNumber);
return View(singlepest);
}
这是我收到错误的 View (没有“IEnumerable”类型的 ViewData 项具有键“PestType”。):
<div class="editor-label">
@Html.LabelFor(model => model.PestType, "Pest Type")
</div>
<div class="editor-field">
@Html.DropDownList("PestType", String.Empty) // here is the error
@Html.ValidationMessageFor(model => model.PestType.ToString())
</div>
现在我看到了一些关于显示枚举的帖子,但我找不到解决我的问题的方法。有人可以给我一些关于如何修复它的建议吗?
感谢您的宝贵时间!
最佳答案
你有 @Html.DropDownList("PestType", String.Empty)
, 但第二个参数需要是 IEnumerable<T>
.您将需要模型中的害虫列表,然后使用 model.Pests
例如 Pets 是 IEnumerable
.
编辑:基于评论...
But I want to display just the various types of pest (Dog, Cat, etc) not all the pests that are in my database
好的,这些分类了吗,你能不能写点类似的东西(手写的,所以检查语法)..
var pests = (from _context.Pests.Where(p => p.CategoryId == 1) select p.PestName).ToList();
如果您需要为枚举获取 IEnumerable(因为我不确定数据库是什么样的),您可以使用...
Enum.GetValues(typeof(PestType))
.OfType<PestType>()
.Where(p => p == ??);
关于c# - 没有具有键 'IEnumerable<SelectListItem>' 的 'PestType' 类型的 ViewData 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781878/