如果您阅读此问题,请注意调试器可能指向与实际错误不同的行,请检查我的答案。
我的控制器中有以下内容:
(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 Entities急切加载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()
。
答案 0 :(得分:0)
确保ViewBag.AppointmentSlot
不为空:
if (ViewBag.AppointmentSlot != null) {
@ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
}
答案 1 :(得分:0)
@ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
</div>
<p>
...
</p>
--> <input type="hidden" name="AppointmentSlotID" value="@ViewBag.AppointmetnSlot.ID" />
调试器显示错误的行。问题是以下错误输入:value="@ViewBag.AppointmetnSlot.ID"
。