用剃刀循环模型

时间:2013-07-06 21:20:23

标签: asp.net-mvc-4 razor

尝试打印出每个电影项目的名称。

例如

         
  • 黑暗骑士

我是否在剃刀代码中遗漏了一些声明性陈述? Intellisense没有列出Model

之后的任何选项
 [XmlRoot("movies")]
      public class MovieSummary
      {
         [XmlElement("movie")]
         public List<Movie> Movies { get; set; }
      }

      public class Movie
      {
         public int id { get; set; }
         public string name { get; set; }
      }

      public ActionResult Index()
      {
         MovieSummary summary = Deserialize();
         return View(summary);
      }

      public static MovieSummary Deserialize()
      {
         using (TextReader reader = new StreamReader("c:\\movies.xml"))
         {
            XmlSerializer serializer = new XmlSerializer(typeof(MovieSummary));
            return (MovieSummary)serializer.Deserialize(reader);
         }
      }

      <?xml version="1.0" ?> 
      <movies xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <movie>
        <id>1</id>
        <name>The Dark Knight</name>
       </movie>
       </movies>

      <ul>
      @if (Model != null) {
           foreach (var movies in Model.Movies) 
           {
                <li>@movies.movie.name</li>
           }
      }
      </ul>

1 个答案:

答案 0 :(得分:11)

在View文件的顶部,按如下方式声明模型类型:

@model MovieSummary

然后迭代您的Movies集合:

<ul>
      @if (Model != null)
      {
           foreach (var movie in Model.Movies)
           {
                 <li>@movie.name</li>
           }
      }
</ul>