在此方案中,如何将信息传递到从索引查看 - MVC3



我写了以下代码:

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 首歌曲应该显示在它下面。我已经想出了如何捕获上面的所有这些信息,但我不确定如何将其传递给显示器。有人可以帮我吗?

我想你应该在你的应用程序中添加一些类。例如,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);
}

你应该填充一个模型对象...并在返回行中传递它:

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

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

@model YourProject.MyModel

然后,执行循环遍历@Model对象。

Q1. 我不确定如何将其传递到视图中 显示器

一个。为此,您需要使用视图模型,下面是我为此准备的视图模型。

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

将您拥有的所有数据推送到此模型中。

问题 2.我正在尝试做的是传递 20 个带有电影图像的电影名称,每部电影都有大约 4 或 5 首歌曲应该显示在它下面

一个。现在,由于您拥有的是电影集合,因此您需要将此 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
}   

希望这有帮助。

最新更新