C# 数据绑定:';System.Web.Mvc.SelectListItem';不包含名为';学生ID';
我拥有以下实体:C# 数据绑定:';System.Web.Mvc.SelectListItem';不包含名为';学生ID';,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我拥有以下实体: public partial class Enrollments { [Key] public int ID { get; set; } public int RegistrationID { get; set; } public int ModuleID { get; set; } [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [D
public partial class Enrollments
{
[Key]
public int ID { get; set; }
public int RegistrationID { get; set; }
public int ModuleID { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Enrollment Date")]
public Nullable<System.DateTime> EnrollmentDate { get; set; }
[Display(Name = "Price Agreed")]
public Nullable<decimal> PriceAgreed { get; set; }
public Nullable<decimal> Grade { get; set; }
[NotMapped]
public virtual Modules Modules { get; set; }
[NotMapped]
public virtual Registrations Registrations { get; set; }
[NotMapped]
[Display(Name = "Student")]
public virtual String StudentName { get; set; }
[NotMapped]
public virtual int StudentID { get; set; }
[NotMapped]
[Display(Name = "Course")]
public virtual String CourseName { get; set; }
[NotMapped]
public virtual int CourseID { get; set; }
[NotMapped]
[Display(Name = "Module")]
public virtual String ModuleName { get; set; }
}
我认为:
<div class="form-group">
@Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.StudentID, (SelectList)ViewBag.StudentNames, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
@LabelFor(model=>model.StudentName,htmlAttributes:new{@class=“controllabel col-md-2”})
@DropDownListFor(model=>model.StudentID,(SelectList)ViewBag.StudentNames,new{htmlAttributes=new{@class=“form control”})
我收到以下错误:数据绑定:“System.Web.Mvc.SelectListItem”不包含名为“StudentID”的属性
我已经检查了许多其他类似的问题,事实上,这段代码基于其中一个答案,但仍然会出现错误。之所以出现此错误,是因为SelectListItem实际上没有属性StudentyID。 将初始化更改为
ViewBag.StudentNames = new SelectList(db.Students.Select(x =>
new SelectListItem
{
Value = x.ID.ToString(),
Text = x.StudentName
}),
"Value",
"Text");
还是像这样
ViewBag.StudentNames = new SelectList(db.Students.Select(x =>
new
{
StudentID = x.ID.ToString(),
StudentName = x.StudentName
}),
"StudentID",
"StudentName");
@谢谢你。。。这是我正在寻找的第二种语法。第一种语法是毫无意义的额外开销-它从第一种语法创建了第二种相同的
IEnumerable
-它只是ViewBag.StudentNames=db.Students.Select(x=>new-SelectListItem{Value=x.ID.ToString(),Text=x.StudentName})代码>
ViewBag.StudentNames = new SelectList(db.Students.Select(x =>
new
{
StudentID = x.ID.ToString(),
StudentName = x.StudentName
}),
"StudentID",
"StudentName");