复杂模型到嵌套列表

时间:2015-06-05 02:12:38

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

我对C#和MVC都很陌生,但我正在尝试使用它来构建日志系统。在输入事件报告之前,用户可以查看页面并从类别列表中选择事件代码

该模型将是:

public class EventCategory {
    public virtual int eventCategoryId {get; set;}
    public virtual string eventText {get; set;}
    public virtual List<EventCode> eventCodes {get; set;}
}

public class EventCode {
    public virtual int eventCodeId {get; set;}
    public virtual string eventCode {get; set;}
    public virtual string eventCodeLongText {get; set;}
    public virtual List<Event> events {get; set;}
}

public class Event {
    public virtual int eventId {get; set;}
    public virtual string eventText {get; set;}
    public virtual DateTime eventTime {get; set;}
}

我的观点应输出:

<ul>
    <li>
        Event category 1
        <ul>
            <li>Event Code 1</li>
            <li>Event Code 2</li>
            <li>Event code 3</li>
       </ul>
    </li>
    <li>
        Event category 2
        <ul>
            <li>Event Code 3</li> <!--They might overlap -->
            <li>Event Code 4</li>
            <li>Event Code 5</li>
        </ul>
   </li>
</ul>

如何使用EF最好地实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果您想使用@ for / @ foreach,那么您需要一个列表 - 这将存在于您尚未包含的控制器中,例如:

Under / Models:

public class ReportViewModel 
{
    public IList<EventCategory> EventCategories { get;set; }
}

在您的控制器中

public ActionResult ReportView()
{
    var model = new ReportViewModel();
    //model.EventCategories = ...
    // however you load from your db, eg: db.EventCategories.LoadAll();

    // This assumes you have your EF relationships and/or DB tier 
    // setup correctly so that load eventcategories 
    // also loads each eventcategory.eventCodes

    // possibly:
    model.EventCategories = db.EventCategories.Include("eventCodes").ToList();

    return View(model);
}

在您看来:

@model ReportViewModel

<ul>
    @foreach(var cat in Model.EventCategories) 
    {
        <li>
            @Html.DisplayFor(x=>cat.eventText)
            <ul>
                @foreach(var code in cat.eventCodes) 
                {
                    <li>
                        @code.eventCode
                    </li>
                }
            </ul>
        </li>
    }
</ul>