0

我写了以下代码:

public ActionResult Index()
        {                            
            var folders = Directory.GetDirectories(Server.MapPath("~/Content/themes/base/songs"));

            foreach (var folder in folders)
            {
                var movieName = new DirectoryInfo(folder).Name;
                string[] files = Directory.GetFiles(folder);
                string img = string.Empty;
                List<string> song = new List<string>();
                foreach (var file in files)
                {
                    if (Path.GetExtension(file) == ".jpg" ||
                        Path.GetExtension(file) == ".png")
                    {
                        img = Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file);
                    }
                    else 
                    {
                        song.Add(Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file));
                    }
                }
            }
            return View();
        }

我想要做的是传递 20 个带有电影图像的电影名称,每部电影都有大约 4 或 5 首歌曲应该显示在它下面。我已经想出了如何捕获上面的所有这些信息,但我不确定如何将其传递给 Display。有人可以帮帮我吗?

4

3 回答 3

1

我猜你应该在你的应用程序中添加一些类。例如 Movie 和 MovieSong,你的 Movie 类应该有类似 IList Images 的东西。然后,您可以轻松地将电影传递给您的视图。

我不确定这段代码是否有效,但你可以尝试这样的事情:

public ActionResult Index()
{   
    var movies = new List<Movie>();

    var songsPath = Server.MapPath("~/Content/themes/base/songs");
    var folders = Directory.GetDirectories(songsPath);

    foreach (var folder in folders)
    {
        Movie movie = new Movie();
        movie.MovieName = new DirectoryInfo(folder).Name

        string[] files = Directory.GetFiles(folder);

        foreach (var file in files)
        {
            if (Path.GetExtension(file) == ".jpg" ||
                Path.GetExtension(file) == ".png")
            {
                movie.Images.Add(Path.Combine(songsPath, file));
            }
            else 
            {
                movie.Songs.Add(Path.Combine(songsPath, file));
            }
        }

        movies.add(movie);
    }
    return View(movies);
}
于 2012-10-11T03:00:41.573 回答
0

Q1。我不知道如何将它传递给显示

A. 您需要为此使用 View Model,下面是我为此准备的 ViewModel。

public class Movie
{
    public string Name;
    public string ImagePath;
    ....
    ....
    //Add more as per your requirement
}

将您拥有的所有数据推送到这个准备好的模型中。

Q2。我想做的是传递 20 个电影名称和电影图像,每部电影都有大约 4 或 5 首歌曲应该显示在它下面

A. 现在您拥有的是电影集合,您需要将此 Movie 类的列表传递给模型。

public ActionResult Index()
{   
    var movies = new List<Movie>();

    // populate the data

    return View(movies);
}

在视图中显示

@model ProjectName.Models.List<Movies>

@foreach(var item in Model)
{
    <h1>Movie Name : </h1> @item.Name
    ....
    .... //etc etc
}   

希望这可以帮助。

于 2012-10-11T04:58:36.607 回答
0

您应该填充模型对象...并将其传递到返回行:

var theModel = new MyModel();
...
//All the loading model info

return View(theModel)

在您的视图中,您需要在顶部设置一行,如下所示:

@model YourProject.MyModel

然后,您对对象进行循环@Model

于 2012-10-11T02:56:34.193 回答