looping through model with razor

2019-06-27 12:35发布

问题:

Trying to just print out the name of each movie item.

eg.

  • The Dark Knight

Am I missing some declarative statement in the razor code? Intellisense doesn't list any options after 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:

At the top of your View file, declare your model type as follows:

@model MovieSummary

Then iterate on your Movies collection:

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