I am very new to ASP.NET MVC so please be kind.
I have a very simple db with three tables Questions, QuestionOptions, Responses.
my pk in Questions is Id and links to questionId in both QuestionOptions and Responses. I also have a field in Questions called pageId, so multiple questions can appear on one page.
I started with this in my controller;
// GET: /Questions/ViewQuestion/5
public ActionResult ViewQuestion(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Question question = db.Questions.Find(id);
if (question == null)
{
return HttpNotFound();
}
return View(question);
}
And my View returns a single question and options perfectly;
@model Template.Models.Question
@{
ViewBag.Title = "Details";
}
<div>
<h4>Question #@Model.questionId</h4>
<hr />
<h1> @Html.DisplayFor(model => model.question1)</h1>
<ul>
@foreach (var item in Model.QuestionOptions)
{
<li>@Html.DisplayFor(modelItem => item.questionOption1)</li>
}
</ul>
But now I am trying to create a view that will display all of the questions with the same pageID - and am getting nowhere.
This is my new ActionResult;
public ActionResult ViewQuestion(int? id)
{
var pageId = id;
var question = from q in db.Questions
where q.pageId == pageId
orderby q.ranking
select new { q.questionId,
q.questionType, q.question1}
;
return View(question.ToList());
}
And my View;
@model IEnumerable<Template.Models.Question>
@{
ViewBag.Title = "View question;";
}
<div>
@foreach (var item in Model) {
<h4>Question </h4>
<hr />
<h1> @Html.DisplayFor(model => item.question1.AsEnumerable())</h1>
<ul>
@foreach (var item in Model.QuestionOptions)
{
<li>@Html.DisplayFor(modelItem => item.questionOption1)</li>
}
</ul>
}
But now it does not recognize QuestionOptions as part of the Model anymore, and even if I comment that section out I still get the error The model item passed into the dictionary is of type -- but this dictionary requires a model item of type System.Collections.Generic.IEnumerable
I know somewhere my syntax is terribly wrong, but I have no idea where after searching for 3 days. Please help!
Question, but your second example is returning an anonymous type. Is this what you intended? You could just change your select toselect q