1

アンケート画面を作成しており、ユーザーの回答とともに質問のあるセクションを表示する必要があります。これが私のモデルです:

** Section *****
 public int SectionID { get; set; }
 public string SectionText { get; set; }

** Question ****
 public int QuestionID { get; set; }
 public int SectionID { get; set; }
 public string QuestionText { get; set; }
 public bool Required { get; set; }
 public int DisplayOrder { get; set; }

** Response ****
 public int ResponseID { get; set; }
 public int UserID { get; set; }
 public int QuestionID { get; set; }
 public string AnswerValue { get; set; }
 public virtual Question Question { get; set; }

LINQ または別の方法でこれを取得して、次のように表示するにはどうすればよいですか。

Section1: User Info
        Question 1. Name:  Bob Smith
        Question 2. Phone: 999-999-9999

Section2: User Tasks
         Question 1. Role: Engineer
         Question 2. Location: Baltimore

私は次のことを試しました(deosは機能しません):

var sections = from b in db.Sections.Include(s => s.Questions.Select(q => q.Responses.Where(r => r.userId == 1))
                            orderby b.SectionOrder
                            select b;
4

1 に答える 1

1
int userId = 1;
var query = from s in db.Sections
            join r in db.Responses.Where(x => x.UserID == userId)
                   on s.SectionID equals r.Question.SectionID into g
            select new SectionModel
            {
                ID = s.SectionID,
                Name = s.SectionText,
                Results = from x in g
                          orderby x.Question.DisplayOrder
                          select new QuestionResultModel
                          {
                              Index = x.Question.DisplayOrder,
                              Question = x.Question.QuestionText,
                              Answer = x.AnswerValue
                          }
            };

  return View(query.ToList());

ViewModel の更新サンプル:

public class SectionModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IEnumerable<QuestionResultModel> Results { get; set; }
}

public class QuestionResultModel
{
    public int Index { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

表示中:

@model IEnumerable<YourApplication.Models.SectionModel>

@foreach (var s in Model)
{
    <div>Section @s.ID : @s.Name</div>

    foreach (var r in s.Results)
    {
        <div>Question @r.Index. @r.Question : @r.Answer</div>    
    }
}
于 2012-12-19T20:13:26.437 に答える