[c#] Cannot perform runtime binding on a null reference, But it is NOT a null reference

using: MVC 4, ASP.NET Razor

I'm getting an error that looks like it shouldn't be possible. It tells me that i'm using a null-reference, States, but clearly it is being set.

Controller:

public ActionResult Index()
{
    Dictionary<int, string> states = new Dictionary<int, string>()
    {
        { -1, "a"},
        { 0, "b"},
        { 1, "c"},
        { 2, "d"},
    };

    //assigning states
    ViewBag.States = states;

    foreach (KeyValuePair<int, string> de in ViewBag.States)
    {
        Debug.WriteLine(de.Key);
    }
    return View();
}

The View:

<div class="search-input">
    <select>
        @foreach (KeyValuePair<int, string> de in ViewBag.States)
        {
            <option value="@de.Key">@de.Value</option>
        }
    </select>
</div>

The error:

Cannot perform runtime binding on a null reference
Line 54: @foreach (KeyValuePair<int, string> de in ViewBag.States)

This question is related to c# asp.net asp.net-mvc razor

The answer is


You must define states not equal to null..

@if (ViewBag.States!= null)
{
    @foreach (KeyValuePair<int, string> de in ViewBag.States)
    {
        value="@de.Key">@de.Value 
    }
}                                

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)


My solution to this error was that a copy and paste from another project that had a reference to @Model.Id. This particular page didn't have a model but the error line was so far off from the actual error I about never found it!


Set

 Dictionary<int, string> states = new Dictionary<int, string>()

as a property outside the function and inside the function insert the entries, it should work.


Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.


This error happens when you have a ViewBag Non-Existent in your razor code calling a method.

Controller

public ActionResult Accept(int id)
{
    return View();
}

razor:

<div class="form-group">
      @Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.Flag(Model.from)
     </div>
</div>
<div class="form-group">
     <div class="col-md-10">
          <input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@ 
     </div>
</div>

For some reason, the .net aren't able to show the error in the correct line.

Normally this causes a lot of wasted time.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC