ฉันใช้ Razor ในแอปพลิเคชัน asp.net ของฉัน จากคอนโทรลเลอร์ของฉัน ฉันใส่ ViewBag ซึ่งเป็นพจนานุกรมแบบนี้:
Dictionary<int, RisposteUtente> mappaRisposte = (Dictionary<int, RisposteUtente>)Session["mappaRisposte"];
if (mappaRisposte == null)
mappaRisposte = new Dictionary<int, RisposteUtente>();
ViewBag.mappaRisposte = mappaRisposte;
ฉันต้องการดึงค่าของพจนานุกรมนี้จากไฟล์ cshtml ดังนั้นฉันจึงสร้างโค้ดนี้:
var oggetto = ((Dictionary<int, AnalisiHRVElaborazioni.Models.Response.RisposteUtente>)ViewBag.mappaRisposte)[x.rowId];
if (oggetto != null)
{
<script>
alert("oggetto " + oggetto.valore);
</script>
}
ดังนั้นหากฉันพยายามเริ่มโค้ดนี้ ฉันพบข้อผิดพลาดนี้:
Exception detail: System.Collections.Generic.KeyNotFoundException: The specified key was not present in the dictionary.
แล้วฉันจะจัดการสถานการณ์นี้ได้อย่างไร?