c# - DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'StudentID'
问题描述
I have the following entity:
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; }
}
And I have this controller action:
public ActionResult Create()
{
ViewBag.StudentNames = new SelectList(db.Students.Select(x =>
new SelectListItem
{
Value = x.ID.ToString(),
Text = x.LastName.Trim() + ", " + x.FirstName
}),
"StudentID",
"StudentName");
return View();
}
In my view:
<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>
I get this error: DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'StudentID'.
I have checked out many other similar problems and, in fact, based this code on one of the answers, but still get the error.
解决方案
您收到此错误是因为 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");
推荐阅读
- google-contacts-api - 有没有办法从 Google Contacts 联系人 ID 获取 Google People API 资源 ID?
- android - androidx.appcompat 库对非 SDK 接口的限制
- python - 这个 Python 程序的错误是什么?
- java - Android:从 BroadcastReceiver 检索到的静态变量与在 MainActivity 中检索到的相同变量不同?
- python - 在 Python 中建模制造风能曲线
- qt - CloudViewer 和 PCLVisualizer 未关闭
- opencv-python - 视频流中的多行跟踪
- spring - 在休眠和 STS 中使用逆向工程更新数据库模式后更新实体类
- django - ISR 在 django 服务器中不工作,但在下一个开发服务器中工作
- php - 嗨,我怎样才能让这个 curl 先通过代理,无论是 socks 4,5 还是 https、http?在php中