IT Share you

Null 참조에서 런타임 바인딩을 수행 할 수 없지만 Null 참조가 아닙니다.

shareyou 2020. 11. 14. 11:19
반응형

Null 참조에서 런타임 바인딩을 수행 할 수 없지만 Null 참조가 아닙니다.


사용 : MVC 4, ASP.NET Razor

불가능한 것 같은 오류가 발생합니다. 그것은 내가 null-reference, States를 사용하고 있다고 말하지만 분명히 설정되고 있습니다.

제어 장치:

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();
}

보기:

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

오류:

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

해결책을 찾았습니다. ViewBag.Typo <-내 뷰에 오타가 있습니다. 이로 인해 오류가 발생했지만 디버거가 관련없는 위치에 예외를 배치했습니다.


이 예외는 리플렉션을 사용하여 존재하지 않는 속성이 동적으로 업데이트 될 때도 발생합니다.

리플렉션을 사용하여 속성 값을 동적으로 업데이트하는 경우 전달 된 PropertyName속성이 실제 속성과 동일한 지 확인하는 것이 좋습니다.

제 경우에는 업데이트를 시도 Employee.firstName했지만 속성은 실제로 Employee.FirstName.

명심할 가치가 있습니다. :)


This error happen when you have a ViewBag nonexistent 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 cause a lot of wasted time.


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!


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 
    }
}                                

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.

참고URL : https://stackoverflow.com/questions/19457804/cannot-perform-runtime-binding-on-a-null-reference-but-it-is-not-a-null-referen

반응형