我正在学习 MVC 和实体框架,所以请承担我的问题...我正在尝试为我的模型类 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; }
}
这是害虫类型:
public enum PestType
{
Dog,
Cat,
Fox,
Rabbit,
Rat
}
这是控制器:
[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);
}
这是我收到错误的视图(没有具有键“PestType”的“IEnumerable”类型的 ViewData 项。):
<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>
现在我看到了一些关于显示枚举的帖子,但我无法找到解决我的问题的方法。请有人给我一些关于如何解决它的建议吗?
感谢您的时间!