How to pass a strongly typed model and a list of models to a view simultaneously

Viewed 958

My end goal is to pass a strongly typed model (to populate a drop-down menu) and a list of models (based on a search query) to a view simultaneously from a controller. The view I am passing it to is the "Clear()" view. Currently in my HomeController.cs I have:

public ActionResult Clear()
    {
        var states = GetAllStates();

        var model = new ProjectClearanceApp.Models.Project();

        model.States = GetSelectListItems(states);

        return View(model);
    }

    private IEnumerable<string> GetAllStates()
    {
        return new List<string>
        {
            "AL",
             // ... (you get the point)
            "WY",
        };
    }

    private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
    {
        var selectList = new List<SelectListItem>();

        foreach (var element in elements)
        {
            selectList.Add(new SelectListItem
            {
                Value = element,
                Text = element
            });
        }

        return selectList;
    }

I read somewhere that that's the best way to get the list of options for a drop-down menu. Now I'd also like a pass a LIST of models to the same view (Clear.cshtml) based on a search query. I'm reading from this Microsoft tutorial to search in the controller action for that view by adding

public ActionResult Index(string searchString)
{
    var movies = from m in db.Movies
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    return View(movies);
}

to the controller. How can I pass both the list of drop-down options AND the list of models that fit the search from the controller to the view (or, how can I achieve the same effect without passing both from the controller)?

2 Answers
Related