EditorFor上可空的DateTime - "可空对象必须具有值QUOT;。 [英] EditorFor on nullable DateTime - "Nullable object must have a value."

查看:86
本文介绍了EditorFor上可空的DateTime - "可空对象必须具有值QUOT;。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图显示一个表单,允许用户输入一个人的一项新的任务。我使用的是DateTime.cshtml EditorTemplate处理DateTime值的分配。非空的日期时间正常工作。可空的DateTime导致InvalidOperationException异常:可空对象必须具有的价值。

I am attempting to display a form that allows a user to input a new assignment for a person. I'm using a DateTime.cshtml EditorTemplate to handle DateTime values for the assignment. The non-nullable DateTime works fine. The nullable DateTime causes an "InvalidOperationException: Nullable object must have a value."

我有一个简单的视图模型,看起来像这样:

I have a simple viewmodel that looks like this:

AssignmentViewModel.cs:

AssignmentViewModel.cs:

public Person Person { get; set; }
public Assignment NewAssignment { get; set; }

Assignment.cs包括:

Assignment.cs contains:

public DateTime AssignmentStartDate { get; set; }
public DateTime? AssignmentEndDate { get; set; }

我AssignmentController Create()方法是这样的:

My AssignmentController Create() method looks like:

public ViewResult Create(int personId)
{
    Person person = personRepository.GetPersonById(personId);
    var newAssignment = new AssignmentViewModel { Person = person, NewAssignment = new Assignment() };
    return View(newAssignment);
}

我Create.cshtml看法是这样的:

My Create.cshtml view looks like this:

@model AssignmentViewModel

@using (Html.BeginForm("Create", "Assignment"))
{
    @Html.Hidden("NewAssignment.PersonId", Model.Person.PersonId)
    @Html.LabelFor(x => x.NewAssignment.AssignmentStartDate):
    @Html.EditorFor(x => x.NewAssignment.AssignmentStartDate.Date, new { cssClass = "datePicker" })
    <br />
    @Html.LabelFor(x => x.NewAssignment.AssignmentEndDate):
    @Html.EditorFor(x => x.NewAssignment.AssignmentEndDate.Value.Date, new { cssClass = "datePicker" })
    <br />
    <input type="submit" value="Send />
}

我DateTime.cshtml EditorTemplate如下:

My DateTime.cshtml EditorTemplate looks like:

@model DateTime?

@{
    String modelValue = "";
    if (Model.HasValue)
    {
        if (Model.Value != DateTime.MinValue)
        {
            modelValue = Model.Value.ToShortDateString();
        }
    }
}

@Html.TextBox("", modelValue, new { @class = "datePicker" })

当我尝试加载创建视图,我上线@ Html.EditorFor(X => x.NewAssignment.AssignmentEndDate.Value)。

When I attempt to load the Create view, I get the exception mentioned above on the line "@Html.EditorFor(x => x.NewAssignment.AssignmentEndDate.Value)".

您可能会奇怪,为什么我传递AssignmentEndDate.Value.Date而不是仅仅传递AssignmentEndDate;的原因是因为我想要去的地方,我分裂成日期时间日期和一个的TimeOfDay场和一个DateTimeModelBinder重组他们的点。我使用了类似的技术来这里显示的和的这里

You may be wondering why I'm passing in AssignmentEndDate.Value.Date instead of just passing in AssignmentEndDate; the reason is because I'm trying to get to the point where I'm splitting DateTime into Date and a TimeOfDay field and recombine them with a DateTimeModelBinder. I am using a similar technique to the one shown here and here.

我-can-跳过错误,通过改变我的控制器Create()方法来实例化AssignmentEndDate视图模型设置为DateTime.MinValue,但这似乎完全错误的可空日期时间:

I -can- bypass the error, by changing my controller Create() method to instantiate the ViewModel with AssignmentEndDate set to DateTime.MinValue, but this seems completely wrong for a nullable DateTime:

var newAssignment = new AssignmentViewModel 
                        { 
                            Person = person, 
                            NewAssignment = new Assignment { AssignmentEndDate = DateTime.MinValue } 
                        };

奇怪的事情发生后,我的旁路通过为可空的DateTime值的误差;联合国要求的为空的日期时间属性(AssignmentEndDate.Date)失败,客户端验证。试图提交表单突出红色的领域。

Something strange happens after I "bypass" the error by supplying a value for the nullable DateTime; the un-required nullable DateTime property (AssignmentEndDate.Date) fails client side validation. Trying to submit the form highlights the field in red.

我该如何正确处理呢?

推荐答案

的问题是,你试图检索 AssignmentEndDate.Value.Date ,而 AssignmentEndDate ,这将导致这个错误。

The problem is that you're trying to retrieve the AssignmentEndDate.Value.Date, but AssignmentEndDate is null, which results in this error.

由于你的编辑模板接受的DateTime?,你应该沿着 AssignmentEndDate 通过。换句话说,删除 .Value.Date 从视图:

Since your editor template accepts a DateTime?, you should just pass along the AssignmentEndDate. In other words, remove the .Value.Date from the view:

@Html.EditorFor(x => x.NewAssignment.AssignmentEndDate, new { cssClass = "datePicker" })

由于编辑器模板使用 ToShortDateString(),没有必要之日起,在所有截断的时间。

Since your editor template is using ToShortDateString(), there's no need to "truncate" the time from the date at all.

关于你渴望拥有独立的日期和时间编辑:

Regarding your desire to have separate "Date" and "Time" editors:

您可以这样做2种方式。

You can do this 2 ways.

1 - ?您当前的的DateTime 编辑器呈现为 Model.Value.Date ,所以你可以现场简单地扩展这个也呈现领域,为 Model.Value.TimeOfDay 。例如:

1 - Your current DateTime? editor renders a field for the Model.Value.Date, so you could simply extend this to also render a field for the Model.Value.TimeOfDay. Example:

@{
  DateTime? modelDate = (Model == null) ? (DateTime?)null : Model.Value.Date;
  TimeSpan? modelTime = (Model == null) ? (TimeSpan?)null : Model.Value.TimeOfDay;
}
@Html.TextBox(..., modelDate, new{@class="datePicker"})
@Html.TextBox(..., modelTime, new{@class="timePicker"})

2 - 你可以在上述功能分割成2个独立的编辑,DateOnly和TimeOnly。然后,更新您的视图同时调用编辑:

2 - You could split the above functionality into 2 separate editors, "DateOnly" and "TimeOnly". Then, update your view to call both editors:

@Html.EditorFor(x => x.NewAssignment.AssignmentEndDate, "DateOnly")
@Html.EditorFor(x => x.NewAssignment.AssignmentEndDate, "TimeOnly")

选择是你的,你是否要保留日期和时间部分分开或一起,但是这是我怎么会去解决这个问题。

The choice is up to you, and whether you want to keep the Date and Time parts separate or together, but this is how I'd go about solving this problem.

这篇关于EditorFor上可空的DateTime - &QUOT;可空对象必须具有值QUOT;。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆