Hi I've been stuck to long on this problem. I've looked at a lot of examples but i cant find what im looking for. Any help is appreciated.
I use the Code-First approach.
I've enabled migration and the database is fine [Student] - [StudentCourse] - [Course].
Scenario: I have two entites -> Student
public class Student { public int Id { get; set; } public string Name { get; set; } public virtual List<Course> Courses { get; set; } }
And Course
public class Course { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual List<Student> Students { get; set; } }
Nothing fancy about that... Ive created a ViewModel ->
public class StudentCourseViewModel { public int Id { get; set; } public string Name { get; set; } public List<Course> Courses { get; set; } }
View:
@model Project.Web.Models.StudentCourseViewModel @{ ViewBag.Title = "Edit"; }
Edit
@using (Html.BeginForm()) { @Html.ValidationSummary(true)
<fieldset> <legend>Student</legend> @Html.HiddenFor(model => model.Id) <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Courses) </div> <div class="editor-field"> @for (int i = 0; i < Model.Students.Count(); i++) { <div style="border: dotted 1px; padding: 5px; margin: 10px;"> @Html.HiddenFor(s => s.Students[i].Id) @Html.LabelFor(s => s.Students[i].Name[i + 1]) @Html.EditorFor(s => s.Students[i].Name) </div> } </div> <p> <input type="submit" value="Save" /> </p> </fieldset> }
Controller Action:
[HttpPost] public ActionResult Edit(CourseStudentViewModel model) { var course = db.Courses.Find(model.CourseId); course.Name = model.CourseName; course.Description = model.CourseDescription; course.Students = model.Students; if (ModelState.IsValid) { db.Entry(course).State = System.Data.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(model); }
(Maby this is were i go wrong...)
Anyway, I want to create a new Student with optional many courses (textboxes -> courseName)
How should i do this?
The main issue is that i always get null values (student is fine, List of courses = NULL) back from my view [httpPost]Create -action.
I'm in need of guidance how to make this approach possible.
Thx J!