I’m just trying to build a view but I’m getting the following error:
System.InvalidOperationException: The
model item passed into the dictionary
is null, but this dictionary requires
a non-null model item of type
‘System.DateTime
Now, I know why this is coming up, the particular field in the database is null, however it is supposed to be, as this is something that is edited at a later date. Here is my code:
Action
public ActionResult View(Int64? Id)
{
ModelContainer ctn = new ModelContainer();
var item = from t in ctn.Items where t.ItemID == Id select t;
return View(Item.First());
}
Main View
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Administrator.Master" Inherits="System.Web.Mvc.ViewPage<myApp.Data.Item>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
View
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% Html.RenderPartial("Details", Model); %>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Header" runat="server">
<h1>Details - <%= Model.MainItem %></h1>
</asp:Content>
Partial View
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<myApp.Data.Item>" %>
<%@ Import Namespace="myApp.Supplier.Web.Extensions" %>
<fieldset>
<legend>Information</legend>
<div class="fieldset">
<%= Html.LabelFor(m => m.MainItem)%>
<%= Html.DisplayFor(m => m.MainItem, "FormTextShort")%><br />
<%= Html.LabelFor(m => m.Supplier.Name)%>
<%= Html.DisplayFor(m => m.Supplier.Name, "FormTextShort")%><br />
<%= Html.LabelFor(m => m.ProductCode)%>
<%= Html.DisplayFor(m => m.ProductCode, "FormTextShort")%><br />
<%= Html.LabelFor(m => m.Product.SubmissionDate)%>
<%= Html.DisplayFor(m => m.Product.SubmissionDate, "FormDateShort")%><br />
<%= Html.LabelFor(m => m.Product.SentForRepair)%>
<%= Html.DisplayFor(m => m.Product.SentForRepair, "FormDateShort")%><br />
</div>
</fieldset>
In this case, the x.Product.SentForRepair date is left null, because at the time of submission, it has not yet been sent away. I have other fields like this, e.g. totalCost, etc however for simplicity I have not included them here. If I comment out the SentForRepair lines, the View displays perfectly with the other information.
I’d be so so grateful if someone could point me in the right direction as to how to get around this error!! 🙂
Inside the Display template you need to check for null (after making it strongly typed to
DateTime?):or if you wanted to simply provide a custom date format you could remove the
FormDateShortdisplay template and decorate your view model property with the[DisplayFormat]attribute:and then simply: