0
傳遞一個對象我有一個教師評分系統。當我創建一個關於教師的新評論時,我有一個dropdownlistfor()列表,可供學生選擇。我希望該下拉列表在提交時傳遞課程對象,但是它只是傳入null並給我一個錯誤。我正在使用一個viewbag來顯示所有可用的課程。如何使用DropDownListFor
型號:
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>
IQueryable Select()中的所有內容看起來都不錯嗎? –
TMan
2012-03-05 03:08:44
給我在IList的SelectListItem錯誤..任何想法爲什麼?名稱空間或類型無法找到它說 – TMan 2012-03-05 03:10:27
是的,你需要改變它填充Model.Courses這就是爲什麼它給你一個錯誤 – Raymund 2012-03-05 03:13:33