首页 > 解决方案 > 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.

标签: c#asp.net-mvcrazor

解决方案


您收到此错误是因为 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");

推荐阅读