0

如果您阅读此问题,请注意调试器可能指向与实际错误所在行不同的行,请查看我的答案。

我的控制器中有以下内容:

(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().


4

2 回答 2

0

确保它ViewBag.AppointmentSlot不为空:

if (ViewBag.AppointmentSlot != null) {
    @ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
}
于 2013-07-02T07:46:55.450 回答
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".

于 2013-07-02T08:54:43.660 回答