我正在使用MVC4 razor View引擎,在我的应用程序中,我试图将项目列表绑定到下拉列表控件。由于某些原因并避免循环引用,我声明的项类型是可为空的。
我的模特:
public class Curriculum
{
public int CurriculumID { get; set; }
[Display(Name="Year")]
public int? SchoolYearID { get; set; }
public virtual SchoolYear SchoolYears { get; set; }
}
public class SchoolYear
{
public int SchoolYearID { get; set; }
[Display(Name="School Year"),MaxLength(250)]
public string Name { get; set; }
public virtual ICollection<Curriculum> Curriculums { get; set; }
}
在上面的SchoolYearId是课程模型中的FK和可空类型。
我的控制器:
public ActionResult Index(int id)
{
ViewBag.SchoolYear = new SelectList(db.SchoolYearRepository.GetAll().ToString(), "SchoolYearID", "Name");
ViewBag.Subject = new SelectList(db.SubjectRepository.GetAll().ToList(), "SubjectID", "Name");
return View();
}
我的观点:
@Html.DropDownListFor(model=>model.SchoolYearID, (IEnumerable<SelectListItem>)ViewBag.SchoolYear, "--")
在运行我的应用程序时抛出以下错误:
问题:如何解决此类问题如何使用razor视图引擎将可空类型对象绑定到下拉列表?
请帮我一个人!
答案 0 :(得分:0)
问题在于我将字符串绑定到DropDownList
DataSource
ViewBag.SchoolYear = new SelectList(db.SchoolYearRepository.GetAll().ToString(), "SchoolYearID", "Name");
字符串没有属性SchoolYearID。
工作了!
ViewBag.SchoolYear = new SelectList(db.SchoolYearRepository.GetAll().ToList(), "SchoolYearID", "Name");