Thank you for your reply. I apologize for all the back-and-forth. I really appreciate you taking the time to help me! This is exactly what I needed!
All of my updated code for future reference (truncated for brevity):
Model:
public class QuestionIndexData
{
public PaginatedList<QuestionAndAnswer> Questions { get; set; }
public IEnumerable<Tag> Tags { get; set; }
public IEnumerable<QuestionTag> QuestionTags { get; set; }
public IEnumerable<Vote> Votes { get; set; }
}
HomeController.cs Index method:
public async Task<IActionResult> IndexAsync(
int? id,
string searchString,
int? pageNumber)
{
//...
ViewData["CurrentFilter"] = searchString;
var viewModel = new QuestionIndexData();
var questions = _context.QuestionAndAnswers
.Include(i => i.Votes)
.Include(i => i.QuestionTags)
.ThenInclude(i => i.Tags)
.AsNoTracking()
.OrderByDescending(i => i.Votes.Count)
.ThenBy(i => i.Modified)
.AsQueryable();
if (!String.IsNullOrEmpty(searchString))
{
questions = questions
.Where(s =>
(s.Question.Contains(searchString) ||
s.Answer.Contains(searchString)));
}
//populates each QuestionAndAnswer with related data (Votes and Tags)
if (id != null)
{
ViewData["QuestionID"] = id.Value;
QuestionAndAnswer question = viewModel.Questions.Where(
i => i.ID == id.Value).Single();
Vote votes = viewModel.Votes.Where(
i => i.ID == id.Value).Single();
viewModel.Tags = question.QuestionTags.Select(s => s.Tags);
}
else
{
viewModel.Tags = _context.Tags
.Include(i => i.QuestionTags)
.AsNoTracking()
.OrderByDescending(t => t.QuestionTags.Count)
.AsQueryable();
}
int pageSize = 3;
return View(new QuestionIndexData
{
Questions = await PaginatedList<QuestionAndAnswer>.CreateAsync(questions.AsQueryable().AsNoTracking(), pageNumber ?? 1, pageSize),
Tags = viewModel.Tags,
Votes = viewModel.Votes
});
}
Home > Index.cshtml View:
@model FrequentlyAskedQuestionsCodeFirst.Models.FaqViewModels.QuestionIndexData
@* ... *@
@foreach (var i in Model.Questions)
{
<div>
<div>
@Html.Raw(i.Question)<br />
@Html.Raw(i.Answer)
<hr />
Votes: @i.Votes.Count()
<hr />
Tags:
@foreach (var t in i.QuestionTags)
{
@t.Tags.TagName
}
</div>
</div>
}
@{
var prevDisabled = !Model.Questions.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.Questions.HasNextPage ? "disabled" : "";
}
<a asp-action="Index" asp-route-pageNumber="@(Model.Questions.PageIndex - 1)" class="btn btn-outline-info @prevDisabled">
Previous
</a>
<a asp-action="Index" asp-route-pageNumber="@(Model.Questions.PageIndex + 1)" class="btn btn-outline-info @nextDisabled">
Next
</a>