Shasapo Shasapo - 1 year ago 229
C# Question

c# dictionary string object get value by key

i'm using C# mvc 4 and i'm making a dictionary to be send and displayed at test.cshtml
i'm new to c# and i have problem with casting the object value Dictionary in the cshtml page.

here's my object class and i send it using viewbag :

Dictionary<string, User> dic = new Dictionary<string, User>();
dic.Add("1", new User { ID_Task = "task1", Agent = "shasapo" });
dic.Add("2", new User { ID_Task = "task2", Agent = "fania" });
dic.Add("3", new User { ID_Task = "task3", Agent = "andre" });
ViewBag.taskDetailVehicle = dic;

and here's my first try in test.cshtml how i get the value :

@if (ViewBag.taskDetailVehicle.ContainsKey("3"))
User test1 = ViewBag.taskDetailVehicle.Where(z => z.Value.ID_Task == "3").FirstOrDefault().Value;
User test2 = ViewBag.taskDetailVehicle.Values.FirstOrDefault(k => k.ID_Task == "3");

But this code is giving me error : "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type".

Then i try other ways :

@if (ViewBag.taskDetailVehicle.ContainsKey("3"))
User test1 = ViewBag.taskDetailVehicle["3"];
<p>test1.ID_Task <br/> test1.Agent </p>

But it's return null..

help me please, is there any way to get the value by key ?

Answer Source

ViewBag is a dynamic object, it doesn't have a specific type at compile time. You need to cast the dynamic object to a dictionary:

var dictionary = ViewBag.taskDetailVehicle as Dictionary<string, User>;


@if (ViewBag.taskDetailVehicle.ContainsKey("3"))
    User test1 = dictionary["3"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download