Fuluza
Fuluza

Reputation: 119

View List from controller to View

I am just trying out stuff, I have items from different models and want to return them to as one(if its possible). I have this ActionResult which returns all products from my database:

  [HttpGet]
    public ActionResult GetAllContents()
    {
        ViewData["listy"] = GetColors();
        var i = (from p in db.tProducts
                select p).ToList();
        return View(i);
    }

and the list is coming from this method

  public List<SelectListItem> GetColors()
    {
        var listy = new List<SelectListItem>();
        var colorList = from a in db.tColors
                         select new SelectListItem
                         {
                             Text = a.id.ToString(),
                             Value = a.name
                         };
        foreach (var item in colorList)
            listy.Add(item);
        return listy;
    }

So how do I display this list as a dropdown on the View?

Upvotes: 0

Views: 40

Answers (2)

Supraj V
Supraj V

Reputation: 977

you can use as below

@Html.DropDownList("listy", ViewData["listy"] as List<SelectListItem>)

Upvotes: 1

TechVision
TechVision

Reputation: 269

You need to parse your object to list of SelectListItem, you can use the following

@Html.DropDownListFor(m => m.Colors, ViewData["listy"] as List<SelectListItem>, "-Colors-", new { })

Upvotes: 1

Related Questions