如何在MVC 5中从Model中读取ICollection

时间:2015-03-27 18:05:08

标签: c# linq entity-framework asp.net-mvc-5 tuples

我需要从View in Model中读取Icollection。我有这种情况。

我有3个课程:替代,问题和问题替代

namespace Models
{
public class QuestionAlternative
{

    public int QuestionAlternativeID { get; set; }
    public int QuestionID { get; set; }
    public int AlternativeID { get; set; }
    public virtual Question Question { get; set; }
    public virtual ICollection<Alternative> Alternative { get; set; }

 }
}

问题

namespace Models
{
public class Question
{
    public int QuestionID { get; set; }
    public int FactorID { get; set; }
    public string Description { get; set; }
    public string Complement { get; set; }
    public int IndexOrder { get; set; }
    public double Weight { get; set; }

    public virtual Factor Factor { get; set; }

     }
    }

替代

namespace Models
{
public class Alternative
{        
    public int AlternativeID { get; set; }
    public string Description { get; set; }
    public double Weight { get; set; }
    public int IndexOrder { get; set; }
     }
    }

我的控制器

namespace Inventario.Controllers
{

public class HomeController : Controller
{
    private InventarioContext db = new InventarioContext();
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Questionnaire()
    {          
        var questionAlternative = db.QuestionAlternatives.Include(qa => qa.Question).Include(qa => qa.Alternative);
        return View("../Equipment/Questionnaire", questionAlternative);
    }
}

}

我的观点

<div class="table-responsive">
@using (Html.BeginForm("getRadioValues", "Equipment", FormMethod.Post))
{
    <table class="table table-bordered table-hover table-striped">

        <thead>
            <tr>
                <th>Nº</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var question in Model.GroupBy(q=>q.Question))
            {
                <tr>

                    <td width="10px"><b>@question.Key.QuestionID - @question.Key.Description</b> </td>
                </tr>
                foreach (var alternative in question)
                {
                    <tr>
                        <td>
                            @Html.RadioButton("radio" + @question.Key.QuestionID, alternative.QuestionAlternativeID, false)@alternative.Alternative.HOW TO ACCESS THE FIELDS OS <Alternatives> LIST
                        </td>

                    </tr>
                }
            }
        </tbody>
    </table>

    <input id="submit" type="submit" value="submit" />
    }

   </div>

在我看来,我为每个问题分组了所有替代方案。我需要访问Alternative类的属性来打印替代品,但它是我模型中的一个集合。怎么做?如何访问公共虚拟ICollection Alternative {get;组;内部模型

1 个答案:

答案 0 :(得分:0)

你实际上是按照你写的方式访问它:@alternative.Alternative。它是一个集合(你正确地提到它),所以你可以通过索引访问或枚举它。+