在MVC视图中访问字典

时间:2013-03-12 08:35:31

标签: asp.net-mvc asp.net-mvc-4 dictionary

这是我的控制器代码,我在其中添加了脚本运行的详细信息并将其传递给我的View。如何在我的视图中访问它并将其转换为表格形式,因为它在字典中?我尝试了很少的东西,但看起来并不乐观,所以我没有发布视图代码。任何通用解决方案都可以。

public ActionResult tab()
    { 

//Febuary runs


        ScriptRun run1 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-1));
        ScriptRun run2 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-1));

        //January runs
        ScriptRun run3 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-2));
        ScriptRun run4 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-2));

        //
        ScriptRun run5 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-1));
        ScriptRun run6 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-1));
        ScriptRun run7 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-1));
        ScriptRun run8 = new ScriptRun("IE","Tech2",DateTime.Now.AddMonths(-1));


        List<ScriptRun> janRuns = new List<ScriptRun>();
        janRuns.Add(run3);
        janRuns.Add(run4);

        Dictionary<string,List<ScriptRun>> runs = new Dictionary<string,List<ScriptRun>>();
        runs.Add("Jan",janRuns);

        return View(runs);



    }

1 个答案:

答案 0 :(得分:0)

将您的模型定义为:

@model Dictionary<string, List<string>>

然后遍历您的模型(您可以将HTML更改为表格式):

@foreach (KeyValuePair<string, List<ScriptRun>> item in this.Model)
{
    <h1>@item.Key</h1>
    <ul>
        @foreach (ScriptRun scriptRun in item.Value)
        {
         <li>@scriptRun.SomePropertyFromScriptRun</li>
        }
    </ul>
}