Search code examples
asp.net-mvc-3razor.netviewdata

MVC3 Pass additional data from ctrl to view


If I were to pass additional data (other than the model) into my view, like say a list of files from a specific folder, whats the best way to do that?

I was thinking something like making a method and return a list into ViewData:

        public List<string> GetFiles(int id, string cat)
    {
        var files = new List<string>();

        var folder = "~/App_Data/uploads/" + cat + "/" + id.ToString();
        foreach (var file in Directory.GetFiles(folder))
        {
            files.Add(file);
        }
        return files;
    }

The controller:

ViewData["files"] = db.GetFiles(id, "random");

The view:

@foreach (var item in ViewData["files"]){ //markup }

First, ive heard that viewdata and viewbag shouldnt be used. Second, this code doesnt work. Something with Viewdata object is not enumerable. Should I make a model class for these files. If so, how? 2 models in one view? Im a bit confused how to do this proberly.


Solution

  • If I were to pass additional data (other than the model) into my view, like say a list of files from a specific folder, whats the best way to do that?

    Write a view model which will contain all the properties your view needs and have your controller action pass this view model to the view. So:

    public class MyViewModel
    {
        public List<string> Files { get; set; }
    
        public string Foo { get; set; }
    
        ... some other properties that your view might need
    }
    

    then the controller:

    public ActionResult Index(int id)
    {
        var model = new MyViewModel
        {
            Files = db.GetFiles(id, "random"),
            Foo = "bar"
        };
        return View(model);
    }
    

    and finally in your strongly typed view:

    @model MyViewModel
    @foreach (var file in Model.Files)
    {
        <div>@file</div>
    }
    
    <div>@Html.DisplayFor(x => x.Foo)</div>