KeyNotFoundException จากไฟล์ cshtml

ฉันใช้ 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.

แล้วฉันจะจัดการสถานการณ์นี้ได้อย่างไร?


person bircastri    schedule 15.01.2020    source แหล่งที่มา


คำตอบ (2)


ข้อความแสดงข้อผิดพลาดระบุว่าไม่พบคีย์ที่ระบุ เป็นไปได้ว่าคุณกำลังส่งค่าจาก x.rowId ที่ไม่ถูกต้อง/ไม่มีอยู่ในพจนานุกรม โดยพื้นฐานแล้วนี่เป็นเหมือนข้อผิดพลาดดัชนีอาร์เรย์อยู่นอกขอบเขต คุณควรตรวจสอบว่ามีรหัสอยู่ก่อนหรือไม่:

var dictionary = ((Dictionary<int, AnalisiHRVElaborazioni.Models.Response.RisposteUtente>)ViewBag.mappaRisposte);
var oggetto = dictionary.ContainsKey(x.rowId) ? dictionary[x.rowId] : null;

คุณได้เช็คอินเป็นโมฆะแล้ว ดังนั้นการดำเนินการนี้น่าจะแก้ไขปัญหาของคุณได้

person gabriel.hayes    schedule 15.01.2020

หรือคุณสามารถใช้วิธี TryGetValue เพื่อตรวจสอบคีย์ว่าง

แทนที่จะเป็นสิ่งนี้

var value = myDict[myKey];

เปลี่ยนเป็น

if (!myDict.TryGetValue(myKey, out data)) {
    Debug.LogError("myDict doesn't have the value");
}
else {
    //do whatever you were planning to do
}

ในกรณีของคุณ

var myDict = (Dictionary<int, RisposteUtente>)ViewBag.mappaRisposte;
var oggetto = myDict.TryGetValue(x.rowId, out data) ? data : null;
person daremachine    schedule 15.01.2020