如果您阅读了这个问题,请注意调试器可能指向与实际错误所在行不同的行,请检查我的答案
我的控制器中有以下内容:
(1) ViewBag.AppointmentSlot = context.AppointmentSlots.Where(s => s.ID == id).Single();
在我看来,我的做法如下:
(2) @ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
它在上面的行(2)上抛出以下异常:
Cannot perform runtime binding on a null reference
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
感谢您的帮助。
编辑:
AppointmentSlot.Day
属于DateTime
类型
AppointmentSlot.StartTime
属于TimeSpan
类型
编辑2:
我可以在调试期间访问ViewBag属性,在引发上述异常时,ViewBag.AppointmentSlot
不是null
。
我曾试图迫使LINQ to实体急于加载AppointmentSlot,但没有成功:
ViewBag.AppointmentSlot = context.AppointmentSlots.Where(s => s.ID == id).ToList().Single();
ViewBag.AppointmentSlot = context.AppointmentSlots.Where(s => s.ID == id).ToList()[0];
两者都会导致DynamicProxy类型(延迟加载)。
编辑3:
对于那些可能想知道的人:我不会从控制器操作重定向到另一个视图,我只是return View()
。
确保ViewBag.AppointmentSlot
不为空:
if (ViewBag.AppointmentSlot != null) {
@ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
}
@ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
</div>
<p>
...
</p>
--> <input type="hidden" name="AppointmentSlotID" value="@ViewBag.AppointmetnSlot.ID" />
调试器显示了错误的行。问题是以下内容输入错误:value="@ViewBag.AppointmetnSlot.ID"
。