我有一个教师评级系统。当我创建一个关于老师的新评论时,我有一个dropdownlistfor()可供学生选择的课程列表。我希望该下拉列表在提交时传递一个课程对象,但它只是传入null并给我一个错误。我正在使用一个viewbag来显示所有可用的课程。
型号:
public class TeachersRatingsWall
{
public int ID { get; set; }
[Range(1, 5, ErrorMessage = "Invalid rating")]
public Int32 StarRating { get; set; }
[Required]
public string PostComment { get; set; }
public DateTime PostDate { get; set; }
[Required]
public string Teacher { get; set; } //? or public Teacher Teacher { get; set; }
public Guid PosterID { get; set; }
public string PosterUserName { get; set; }
//[Required]
public Course Course { get; set; }
public Guid CourseID { get; set; }
}
}
Ropository:
public IQueryable<TeachersRatingsWall> Select()
{
return table.Select(x => new TeachersRatingsWall
{
ID = x.ID,
StarRating = x.StarRating,
PostComment = x.PostComment,
PostDate = x.PostDate,
Teacher = x.Teacher,
PosterID = x.PosterID,
CourseID = x.CourseID,
Course = new Course {
ID = x.CourseID,
CourseNumber = x.CourseEntity.CourseNumber,
Department = x.CourseEntity.Department,
Description = x.CourseEntity.Description,
Name = x.CourseEntity.Name
}
});
}
控制器:
public ActionResult Create()
{
ViewBag.allcourses = coursesservice.GetAllCoursesNamesAndNumbers().Select(x => x.Department + " " + x.CourseNumber);
//-----------------------------------------------------------------------------------------------------------
return View();
}
[HttpPost]
public ActionResult Create(TeachersRatingsWall collection)
{
try
{
// TODO: Add insert logic here
collection.PosterID = ((Guid)Membership.GetUser().ProviderUserKey);
collection.PostDate = System.DateTime.Now;
teacherratingservice.CreateComment(collection);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
查看 - Create.cshtml
<div class="editor-label">
@Html.Label("Course:")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Course, new SelectList(ViewBag.allcourses))
</div>
答案 0 :(得分:2)
在您的模型上,您需要以下
public int CourseId { get; set; }
和
public IList<SelectListItem> Courses { get; set; }
在您的控制器上,您必须将这两个模型项目填充在一起,然后在您的视图中它应该是这样的
@Html.DropDownListFor(model => model.CourseId, Model.Courses, "")
MVC将为您自动映射,并为GET和POST选择必要的项目