Loop through a razor model

Trying to simply print the name of each movie element.

eg.

  • The Dark Knight

Is there any missing declarative instruction in the razor code? Intellisense does not list any parameters 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> 
+4
source share
1 answer

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

 @model MovieSummary 

Then go to your Movies collection:

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

Source: https://habr.com/ru/post/1490069/


All Articles