Reputation: 634
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="[email protected]">@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="[email protected]">@(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="[email protected]">@FormatNullableDate(item.DateClosed)</span>
The only way I can get it to work is by putting my @if()
logic like this:
<span id="[email protected]">@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.
Upvotes: 0
Views: 113
Reputation: 634
I don't know what about the the client server separation makes me forget the basics, but this is a simple matter of extending the model to include a string parameter to get the date value:
public string sDateClosed
{
get { return DateClosed.HasValue ? DateClosed.Value.ToString("yyyy-MM-dd") : string.Empty; }
set { DateClosed = DateTime.Parse(value); }
}
I created a partial class file for the model class and added a parameter that returns the nullable field as a string value. Bind this parameter to the view and everything works.
Upvotes: 0