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

时间:2012-10-11 02:44:13

标签: c# asp.net-mvc-3

我写了以下代码:

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首应该显示的歌曲。我已经弄清楚如何捕获上面的所有这些信息,但我不知道如何将其传递到视图中显示。有人可以帮助我吗?

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

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

return View(theModel)

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

@model YourProject.MyModel

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

答案 2 :(得分:0)

<强> Q1。我不知道如何将其传递到显示

的视图中

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

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

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

<强> Q2。我想要做的是传递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
}   

希望这有帮助。