-1

I create a viewbag as below

Dictionary<string, long> actlist = new Dictionary<string, long>();

foreach()
{
 //filling the dictionary
}

 ViewBag.act_type = new SelectList(actlist, "Value", "Key");

In the view call the view bag as below

@Html.DropDownList("acttype", new SelectList(ViewBag.act_type, "Value","Key"))

It's giving an error as below

SelectList does not contain a property with the name 'Key'

What I am missing here?

Sachu
  • 7,555
  • 7
  • 55
  • 94
  • It would need to be `@Html.DropDownList("acttype", new SelectList(ViewBag.act_type, "Value","Text"))` But its already a `SelectList`, so its pointless extra overhead to convert it to `SelectList` again. –  May 13 '18 at 06:39
  • @StephenMuecke ya thanks..sort it out `@Html.DropDownList("acttype", (SelectList)(ViewBag.act_type))` – Sachu May 13 '18 at 07:06
  • Great. Now move from beginner, and start using a view model (which will contain a property `IEnumerable ActTypeOptions` so its `@Html.DropDownList("acttype", Model.ActTypeOptions)` - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  May 13 '18 at 07:31
  • @StephenMuecke thanks..implemented the same :) – Sachu May 13 '18 at 08:06

1 Answers1

0

You are creating the SelectList twice. When you set drop down list, pass the SelectList that you already created.

Add the dictionary to the ViewBag

ViewBag.act_type = actlist;

Then create the SelectList

@Html.DropDownList("acttype", new SelectList(ViewBag.act_type, "Value","Key"))

In what you have, you are trying to create a new SelectList from first one.

Ryan S
  • 521
  • 2
  • 6
  • `'System.Web.Mvc.HtmlHelper<>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched` – Sachu May 13 '18 at 06:15
  • i got the answer..a slight change in ur first code `@Html.DropDownList("acttype", (SelectList)(ViewBag.act_type))` – Sachu May 13 '18 at 06:27