我正在使用C#asp.net mvc 4,我正在发送一个字典并在test.cshtml上显示 我是c#的新手,我在cshtml页面中投射对象值Dictionary时遇到问题。
这是我的对象类,我使用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;
这是我在test.cshtml中第一次尝试获取值:
@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");
}
但是这段代码给了我错误:&#34;不能将lambda表达式用作动态调度操作的参数,而不先将其转换为委托或表达式树类型&#34;。
然后我尝试其他方式:
@if (ViewBag.taskDetailVehicle.ContainsKey("3"))
{
User test1 = ViewBag.taskDetailVehicle["3"];
<p>test1.ID_Task <br/> test1.Agent </p>
}
但它返回null ..
请帮助我,有没有办法按键获取价值?
答案 0 :(得分:1)
ViewBag
是dynamic
对象,它在编译时没有特定类型。您需要将动态对象强制转换为字典:
var dictionary = ViewBag.taskDetailVehicle as Dictionary<string, User>;
然后:
@if (ViewBag.taskDetailVehicle.ContainsKey("3"))
{
User test1 = dictionary["3"];
}