I am getting this error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference
When I try to include nullable DateTime fields in my WebGrid and cannot find any workarounds. I have DateTime values that may always be null, and this is by design. Here is the grid column that offends:
MeetingDetailsGrid.Column(header: "Date",
format: @<span>
<span id="spanDateOpen_@item.ID">@item.DateOpen.ToString("yyyy.MM.dd")</span>
@Html.TextBox("miDateOpen_"+(int)item.ID,(string)item.DateOpen.ToString("yyyy-dd-MM"), new {@type = "date", @style = "display:none"})
THIS NEXT LINE GIVES THE EXCEPTION
<span id="spanDateClosed_@item.ID">@(item.DateClosed!=null ? item.DateClosed.Value.ToString("yyyy-dd-MM") : " ")</span></span>) <--this line
The open date will always have a value, as for a new item it is set to DateTime.Today
but the closed date can remain null and this webgrid is extended to allow for setting that date in the future. I have seen some examples with the inline if else so I have added that: @(item.DateClosed!=null ? item.DateClosed.Value.ToString("yyyy-dd-MM") : ""
(I want the string formatting as well) here when the value is not null. But this gives the same exception.
Using item.DateClosed.HasValue()
in the inline if else macro also yields the error. This is all occurring in the WebGrid.GetHtml( . . . grid.Column) portion of my partial Razor view.
I also found a suggestion here to add a function to call to check the value and return an empty string if it is null:
@functions{
string FormatNullableDate(DateTime? value) => value.HasValue ? value.Value.ToString("MM/dd/yyyy") : "-";
}
And tried to use it like so, and still get the error:
<span id="spanDateClosed_@item.ID">@FormatNullableDate(item.DateClosed)</span>
The only way I can get it to work is by putting my @if()
logic like this:
<span id="spanDateClosed@item.ID">@if(item.DateClosed != null) {item.DateCLosed;}</span>
But this way the user cannot enter a close date easily (I would need to provide another button or something to hit to then enter a close date). Is there really no way to bind a nullable field to a grid when the value is null? I think this will work if the first item in the collection had a proper closed date, but that will definitely not always be the case.