MVC 错误:传递到字典中的模型项为 null

发布于 2024-10-15 06:47:16 字数 2503 浏览 2 评论 0原文

我只是想构建一个视图,但出现以下错误:

System.InvalidOperationException: 传递到字典中的模型项 为空,但该字典要求 类型的非空模型项 '系统.日期时间

现在,我知道为什么会出现这种情况,数据库中的特定字段空,但它应该是空的,因为这是稍后编辑的内容。这是我的代码:

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>

在这种情况下,x.Product.SentForRepair 日期保留为空,因为当时已提交,尚未发送。我还有其他类似的字段,例如totalCost 等,但为了简单起见,我没有将它们包含在这里。如果我注释掉 SentForRepair 行,视图将与其他信息完美显示。

如果有人能指出我正确的方向来解决这个错误,我将非常感激! :)

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!! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

悟红尘 2024-10-22 06:47:16

在显示模板中,您需要检查 null(在将其强类型化为 DateTime? 后):

<% if (Model.HasValue) { %>
    <%= Html.Encode(Model.Value.ToString("yyyy-MM-dd")) %>
<% } %>

或者如果您想简单地提供自定义日期格式,您可以删除 FormDateShort 显示模板并使用 [DisplayFormat] 属性装饰您的视图模型属性:

[DisplayFormat(NullDisplayText = "", DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? SentForRepair { get; set; }

然后简单地:

<%= Html.DisplayFor(m => m.Product.SentForRepair)%>

Inside the Display template you need to check for null (after making it strongly typed to DateTime?):

<% if (Model.HasValue) { %>
    <%= Html.Encode(Model.Value.ToString("yyyy-MM-dd")) %>
<% } %>

or if you wanted to simply provide a custom date format you could remove the FormDateShort display template and decorate your view model property with the [DisplayFormat] attribute:

[DisplayFormat(NullDisplayText = "", DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? SentForRepair { get; set; }

and then simply:

<%= Html.DisplayFor(m => m.Product.SentForRepair)%>
司马昭之心 2024-10-22 06:47:16

我在这里找到了另一个解决方案。将值设置为可为空。

Telerik MVC Grid - 可空 DateTime 属性的问题

@model System.DateTime?

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, 
    new { data_datepicker = true });

I found another solution here. Set value to be nullable.

Telerik MVC Grid - problem with nullable DateTime property

@model System.DateTime?

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, 
    new { data_datepicker = true });
你穿错了嫁妆 2024-10-22 06:47:16

将日期时间的自定义编辑器模板从 DateTime 类型更改为可为 null 的日期时间类型(DateTime?)

@model System.DateTime?

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
                      new { @class = "text-box single-line", data_datepicker="true"})

Change your custom Editor template for datetime from type DateTime to type nullable datetime (DateTime?)

@model System.DateTime?

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
                      new { @class = "text-box single-line", data_datepicker="true"})
失而复得 2024-10-22 06:47:16

刚刚更改了您的 FormDateShort 模板,以便它接受日期时间?而不是 DateTime 并放入一些逻辑来检查渲染之前是否有一个值。

Just changed your FormDateShort template so it takes in a DateTime? rather than a DateTime and put in some logic to check that you have a value before rendering.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文