所以我有适用于学生和课程的应用程序。创建课程时,我已经对学生进行了多次选择,但是现在我也想将选定的用户添加到EditView中。
因此,在我的模型中,有public List<int> Izabrani { get; set; }
用来保存选定的学生参加课程。 (未映射)
namespace KurseviApp
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class Kurs
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Kurs()
{
this.Student = new HashSet<Student>();
}
public int PK_Kurs_ID { get; set; }
public string Naziv_Kursa { get; set; }
[NotMapped]
public List<int> Izabrani { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Student> Student { get; set; }
}
}
我不知道为什么这不可能,它给我错误KurseviApp.Kurs.Izabrani.get返回null。
此行kurs.Izabrani.Add(ids);
// GET: Kurs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Kurs kurs = db.Kurs.Find(id);
List<Student> students = new List<Student>();
foreach (var student in kurs.Student)
{
students.Add(student);
int ids = student.PK_Student_ID;
kurs.Izabrani.Add(ids);
}
ViewBag.Studenti = students.Where(p => p.PK_Student_ID != null)
.Select(p => new SelectListItem
{
Text = p.Ime + "_" + p.Prezime,
Value = p.PK_Student_ID.ToString()
});
if (kurs == null)
{
return HttpNotFound();
}
return View(kurs);
}