简体   繁体   中英

RuntimeBinderException 'Cannot perform runtime binding on a null reference' in MVC code

In the line of code:

<div class="col-md-11 bky-points-summary-body-content">
    @Html.Raw(model.GetRawValue("body").ToString().Replace("[XXX]", (200 - ViewBag.CurrentBalance).ToString()))
</div>

I am getting the exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'

I've tried to re-arrange the code a little by changing the places of the reference to the ViewBag, etc. but nothing seems to help.

RuntimeBinderException often occurs when ViewBag property has null value, in this case ViewBag.CurrentBalance has null value (and you cannot subtract integer value with null).

Try using null coalescing operator for ViewBag.CurrentBalance with a default value when ViewBag.CurrentBalance is null, or assign it from controller action:

@Html.Raw(model.GetRawValue("body").ToString().Replace("[XXX]", 
         (200 - (ViewBag.CurrentBalance ?? 0)).ToString()))

Note that operator precendence for null-coalescing operator ( ?? ) is lower than subtraction operator ( - ), hence you should use parenthesis/brackets around null-coalescing operator for higher priority.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM