I rewrote a portion of my MVC application the other day and now I'm getting a RuntimeBinderException stating 'Cannot perform runtime binding on a null reference.'
I am assigning the ViewBag variable AvailableDocuments a collection (Dictionary) in the Controller and iterating through it in the View. I can make it through the first loop just fine, but when the code reaches the exit point of the second for loop it throws this exception. I have rewritten this a few different ways and always run into the same issue. The only way that I can get rid of this exception is to remove the second/third loops from this View. Also, I have used the debugger to verify that I am not receiving any null values in the collection and that the first loop isn't (for no reason) performing changes to this collection.
@foreach (KeyValuePair<int, string> doc in ViewBag.AvailableDocuments)
{
<option value="@doc.Key" @((ViewBag.Product.Documents[0].OriginalDocID == doc.Key) ? "selected" : "")>@doc.Value</option>
}
This is the for loop that is repeated three times (to fill three dropdowns). The only thing that is changing is the index of Documents (which is not null).
Line 62: <select name="Doc1" style="width:300px;">
Line 63: <option value="-1">Don't Display a Document</option>
Line 64: @foreach (KeyValuePair<int, string> doc in ViewBag.AvailableDocuments)<--BREAK LINE
Line 65: {
Line 66: <option value="@doc.Key" @((ViewBag.Product.Documents[0].OriginalDocID == doc.Key) ? "selected" : "")>@doc.Value</option>'
And the message:
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
ViewBag.ProductandViewBag.Product.Documents[0]. Double check them.