You find this difficult because you are not using the full power of the MVC environment, so let me introduce a working example.
, :
public class SubjectGradesViewModel
{
public SubjectGradesViewModel()
{
Subjects = new List<Subject>();
}
public List<Subject> Subjects { get; set; }
}
:
public class Subject
{
public int Id { get; set; }
public string Name { get; set; }
public List<Student> StudentEntries { get; set; }
}
, :
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Grade { get; set; }
}
, . , , , :
public ActionResult Index()
{
var model = new SubjectGradesViewModel();
var compsci = new Subject
{
Id = 1,
Name = "Computer Science",
StudentEntries = new List<Student>()
{
new Student { Id = 1, Name = "CompSci 1" },
new Student { Id = 2, Name = "CompSci 2" },
}
};
var maths = new Subject
{
Id = 2,
Name = "Mathematics",
StudentEntries = new List<Student>()
{
new Student { Id = 3, Name = "Maths 1" },
new Student { Id = 4, Name = "Maths 2" },
}
};
model.Subjects.Add(compsci);
model.Subjects.Add(maths);
return View(model);
}
[HttpPost]
public ActionResult Index(SubjectGradesViewModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Success");
}
return View(model);
}
, , . Index:
@model SubjectGradesViewModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.EditorFor(m => m.Subjects) <br />
<input type="submit" />
}
, Html.EditorFor, Subjects. , , , EditorTemplate Subject. . , EditorTemplates DisplayTemplates MVC, .
: Subject Student. :
EditorTemplates (, Home\Index.cshtml, Home\EditorTemplates).- , (.. ,
Subject.cshtml Student.cshtml ( , )).
Subject.cshtml :
@model Subject
<b>@Model.Name</b><br />
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.Name)
@Html.EditorFor(m => m.StudentEntries)
Student.cshtml :
@model Student
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.Name)
@Html.DisplayFor(m => m.Name): @Html.EditorFor(m => m.Grade)
<br />
. , POST, , .
, EditorTemplates , DisplayTemplates? , .
- , Html.EditorFor Html.DisplayFor, , , . , , . null Count(), . , .
EditorTemplates , POST . , , . , , .