Ok so this is a follow-up from MVC 5 ASP.NET Entity Framework Collect Form Data through Range Input , My Database Structure Consists of a Survey Having Many Categories, A Ca
This might point you in the right direction, its using lambda expressions.
List<SurveyVM> surveys = DbContext.Survey.Select(s=> new SurveyVM {
ID = s.ID,
Name = s.Name,
Categories = s.Category.Select(c => new CategoryVM {
ID = c.ID,
Name = c.Name,
Questions = c.Question.Select(q=> new QuestionVM {
ID = q.ID,
Title = q.Title,
Score = q.Score
}).ToList()
}).ToList()
}).SingleOrDefault();
This is off the top of my head as I dont have anything to test it with.
Also as a side note I would look at using EditorTemplates/DisplayTemplates instead of your loop in your view as it will make your code easier to read.
for (int i = 0; i < Model.Categories.Count; i++)
{
<div class="category">
@Html.HiddenFor(m => m.Categories[i].ID)
@Html.DisplayFor(m => m.Categories[i].Name)
@for (int j = 0; j < Model.Categories[i].Questions.Count; j++)
{
<div class="question">
@Html.HiddenFor(m => m.Categories[i].Questions[j].ID)
@Html.DisplayFor(m => m.Categories[i].Questions[j].Title)
@Html.TextBoxFor(m => m.Categories[i].Questions[j].Score)
<div class="slider"></div>
</div>
}
<div class="buttons">
<button type="button" class="next">Next</button>
<button type="button" class="previous">Previous</button>
</div>
</div>
}
When you have Domain models and each of domain model have a lot of view models then it is the right time to use Automapper
. All documentation you can find here:
https://github.com/AutoMapper/AutoMapper/wiki/Getting-started