I'm writing a web-app with .NET Core MVC (dotnet version 1.0.4).
I want to pass a Dictionary<string, string>
in a ViewData
object from controller to view and bind it to <select>
element.
This is a result that I want to get:
And I tried two ways to achieve it.
1st way
Controller's code
Dictionary<string, string> animals = new Dictionary<string, string>();
animals.Add("1", "cat");
animals.Add("2", "dog");
animals.Add("3", "bunny");
ViewData["animals"] = new SelectList(animals);
Views's code
<select asp-for="Animal_id" asp-items="(SelectList)@ViewData["animals"]" class="form-control"></select>
That gives me this result
2nd way
Controller's code
Dictionary<string, string> animals = new Dictionary<string, string>();
animals.Add("1", "cat");
animals.Add("2", "dog");
animals.Add("3", "bunny");
ViewData["animals"] = new SelectList(animals.Select(r => new SelectListItem
{
Text = r.Key,
Value = r.Value
}));
Views's code
The same.
That gives me this result:
Apparently, something I don't understand about this concept, although I feel like I'm on a right track. Can you please help me - what needs to be done in order to get the result from my first picture (<option>
s with value
s)?
ViewData["animals"] = new SelectList(animals. "Key", "Value");
to generate the correct<option>
elements – user3559349 Aug 14 '17 at 21:43