I have a teacher rating system. When I got to create a new comment about a teacher, I have a dropdownlistfor() list of classes that are available to the student can choose from. I want that dropdownlist to pass a Course Object in upon submitting but instead it’s just passing in null and giving me an error. I’m using a viewbag to display all the available courses.
Model:
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
}
});
}
Controller:
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();
}
}
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>
On your model you need the following
and
On your Controller you have to populate these two model items together then in your view it should be something like this
MVC will auto map that for you and select the necessary items for GET and POST