Reputation: 3852
The problem I am working on is very similar to the way StackOverflow is displaying Question, its comments, Posts and comments related to the Posts. The hierarchy is the same.
How is this accomplished in ASP.Net MVC?
So far I have this: (I have named the files similar to SO site to make my question more readable)
Views/Questions/Details.aspx
public class QuestionsController : Controller
{
public ActionResult Details(int? questionId)
{
Question question= _db.Question .First(i => i.QuestionId== questionId);
return View(question);
}
}
This loads the details and display the question.
I have a user control called QuestionComment, which should display the comments for the question but I am not sure how to go about wiring it up. I have been using the Dinners solution as a guide.
Upvotes: 1
Views: 654
Reputation: 28153
Create ViewModel for displaying Question with Comments. Something like this:
public class QuestionViewModel
{
public Question Question { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
your controller become:
public class QuestionsController : Controller
{
public ActionResult Details(int? questionId)
{
var question = _db.Question.First(x => x.QuestionId == questionId);
var comments = _db.Comment.Where(x => x.QuestionId == questionId).ToList();
var model = new QuestionViewModel {
Question = question,
Comments = comments
};
return View("Details", model);
}
}
your "Details" View:
<%@ Page Inherits="System.Web.Mvc.ViewPage<QuestionViewModel>" %>
<% Html.Renderpartial("QuestionControl", model.Question); %>
<% Html.Renderpartial("CommentsControl", model.Comments); %>
"QuestionControl" partial View:
<%@ Control Inherits="System.Web.Mvc.ViewUserControl<Question>" %>
<h3><%= Model.Title %></h3>
...
"CommentsControl" partial View:
<%@ Control Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Comment>>" %>
<ul>
<% foreach (var comment in Model) { %>
<li>
<%= comment.Content %>
</li>
<% } %>
</ul>
...
Upvotes: 4
Reputation: 22760
In your view write something like this;
<% foreach (var question in Model.Questions) { %>
<%=question.bodyText%>
<%}%>
Hope this helps, if not post a comment and I'll be less cryptic.
Upvotes: 0