c# - Bind a Razor select to a Dictionary from VewData -


i'm writing web-app .net core mvc (dotnet version 1.0.4).

i want pass dictionary<string, string> in viewdata object controller view , bind <select> element.

this result want get:

enter image description here

and tried 2 ways 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 result

enter image description here

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 result:

enter image description here

apparently, don't understand concept, although feel i'm on right track. can please me - needs done in order result first picture (<option>s values)?

you using overload of selectlist constructor parameter ienumerable. overload calls .tostring() method of each item in collection, , because complex objects, results seeing. overload useful if collection ienumerable<string>.

you need use overload accepts arguments datavaluefield , datatextfield defines properties used options value , display text.

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, "key", "value"); 

note in 2nd example, have generated ienumerable<selectlistitem> use new selectlist(...) create identical ienumerable<selectlistitem> first 1 pointless ovehead , can be

viewdata["animals"] = animals.select(r => new selectlistitem {     text = r.key,     value = r.value })); 

and in view asp-items="(ienumerable<selectlistitem>)@viewdata["animals"]"


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -