0

I want to make a dropdown list based on values from 2 columns, Id and Name, so I want it to be like <option value=Id">Name</option>, not just Name.

I can get just the names like so which is fine:

var result = from r in db.Categories
                         select r.Name;

            ViewBag.Categories = result;

@Html.DropDownListFor(model => model.Name, new SelectList(ViewBag.Categories), "Select Category")

But I want to have both ids and names as I already said, so I change my linq to be:

var result = from r in db.Categories
                         select new { r.Name, r.Id };

But I don't know how to make a dropdown with it with both id and name?

Cœur
  • 37,241
  • 25
  • 195
  • 267
frc
  • 548
  • 2
  • 10
  • 20
  • `ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");` and in the view `@Html.DropDownListFor(m => m.Name, new (SelectList)ViewBag.Categories, "Select Category")` –  Nov 07 '16 at 09:04
  • I get a red line under `(SelectList)` in the view saying it's a type which is not valid in current context. – frc Nov 07 '16 at 09:09
  • Sorry - remove `new` in front of it –  Nov 07 '16 at 09:10
  • That;s it, thanks! Why not put this as the answer, this is important for newbies like me? Also, how would I loop thru that ViewBag in the view to get both the id and name out of it, if you dont mind? – frc Nov 07 '16 at 09:13
  • What do you mean _loop thru that ViewBag_ - why would you want to do that? (and also refer [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o)) –  Nov 07 '16 at 09:15
  • I think it's good to know. I mean if I assign the query result to the ViewBag as in the original, e.g. iewBag.Categories = result; and then go thru it in the view and get the id and name for each row. – frc Nov 07 '16 at 09:20
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127523/discussion-between-stephen-muecke-and-frc). –  Nov 07 '16 at 09:21

1 Answers1

0

You can make a custom SelectList in your Action and put it in a ViewBag before returning the result.

ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");

This will make a list for you based on db.Categories and put the values of the Id column into "value" and Name as textnode.
If you want to change the textnode, you'll need to create a custom list, e.g.:

List<Categorie> temp = db.Categories.ToList();
Foreach (var t in temp)
   t.Name = String.Format("{0} {1}", t.Id, t.Name);
ViewBag.Categories = new SelectList(temp, "Id", "Name");

Don't forget to parse the ViewBag into a SelectList when calling in a view.

@{
SelectList categories = ViewBag.Categories as SelectList;
}

@Html.DropDownListFor(model => model.Name, categories)
Stef Geysels
  • 1,023
  • 11
  • 27