MVC 代码中的 RuntimeBinderException 'Cannot perform runtime binding on a null reference'
RuntimeBinderException 'Cannot perform runtime binding on a null reference' in MVC code
在代码行中:
<div class="col-md-11 bky-points-summary-body-content">
@Html.Raw(model.GetRawValue("body").ToString().Replace("[XXX]", (200 - ViewBag.CurrentBalance).ToString()))
</div>
我遇到异常:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform
runtime binding on a null reference'
我尝试通过更改对 ViewBag 的引用的位置等来稍微重新安排代码,但似乎无济于事。
RuntimeBinderException
通常在 ViewBag
属性 具有空值时出现,在这种情况下 ViewBag.CurrentBalance
具有空值(并且您不能用空值减去整数值)。
当 ViewBag.CurrentBalance
为空时,尝试为 ViewBag.CurrentBalance
使用默认值的空合并运算符,或者从控制器操作中分配它:
@Html.Raw(model.GetRawValue("body").ToString().Replace("[XXX]",
(200 - (ViewBag.CurrentBalance ?? 0)).ToString()))
请注意,空合并运算符 (??
) 的 operator precendence 低于减法运算符 (-
),因此您应该在空合并周围使用 parenthesis/brackets更高优先级的运算符。
在代码行中:
<div class="col-md-11 bky-points-summary-body-content">
@Html.Raw(model.GetRawValue("body").ToString().Replace("[XXX]", (200 - ViewBag.CurrentBalance).ToString()))
</div>
我遇到异常:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'
我尝试通过更改对 ViewBag 的引用的位置等来稍微重新安排代码,但似乎无济于事。
RuntimeBinderException
通常在 ViewBag
属性 具有空值时出现,在这种情况下 ViewBag.CurrentBalance
具有空值(并且您不能用空值减去整数值)。
当 ViewBag.CurrentBalance
为空时,尝试为 ViewBag.CurrentBalance
使用默认值的空合并运算符,或者从控制器操作中分配它:
@Html.Raw(model.GetRawValue("body").ToString().Replace("[XXX]",
(200 - (ViewBag.CurrentBalance ?? 0)).ToString()))
请注意,空合并运算符 (??
) 的 operator precendence 低于减法运算符 (-
),因此您应该在空合并周围使用 parenthesis/brackets更高优先级的运算符。