0

マイページのセクションにポーリングを表示したいので、そのためにこれらの POCO クラスを作成しました。

public class Polls
{
    public int Id { get; set; }
    public string Question { get; set; }
    public bool Active { get; set; }
    public IList<PollOptions> PollOptions { get; set; }
}

public class PollOptions
{
    public int Id { get; set; }
    public virtual Polls Polls { get; set; }
    public string Answer { get; set; }
    public int Votes { get; set; }
}

そして、私は ViewModel の下で使用しました:

public class PollViewModel
{
    public int Id { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

次に、上記の ViewModel を使用してモデルを View に渡しました。

public ActionResult Index()
{
    var poll = from p in db.Polls
               join po in db.PollOptions on p.Id equals po.Polls.Id
               where p.Active == true
               select new PollViewModel { 
                   Id=p.Id,
                   Question=p.Question,
                   Answer=po.Answer
    };

    return View(model);
}

Question表示したいビューとAnswerポーリングで、次のコードを試しました:

@section Polling{
    @foreach (var item in Model.Polls)
    {
        <input type="radio" /> @item.Answer
    }
}

上記のコードは正しく機能しますが、次のようなものも表示したいQuestion:

@section Polling{
    **@Model.Polls.Question**
    @foreach (var item in Model.Polls)
    {
        <input type="radio" /> @item.Answer
    }
}

どうやってやるの?

PS: ホームページに表示するために、ポーリング テーブルに 1 つの行があります。

4

1 に答える 1

1

There is relationship between Polls and PollsOption. So get Polls from your db. And pass it to view. Also you already have PollsOptions that connected to to their Polls. No need to join two tables.

controller

public ActionResult Index()
{
    // get active Polls
    var poll = from p in db.Poll
               where p.Active == true
               select p;

    // pass it to the view
    return View(poll);
}

view

@model IEnumerable<Polls>

@section Polling{
    @foreach (var question in Model)
    {
        <h2>@question.Question</h2>
        @foreach(var answer in question.PollOptions)
        {
            <input type="radio" /> @answer.Answer
        }
    }
}
于 2013-03-04T11:59:29.137 に答える