EditorFor on nullable DateTime - “Nullable object must have a value.”

前端 未结 3 1150
醉梦人生
醉梦人生 2021-01-03 09:43

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 a

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 10:03

    UPDATE: GetValueOrDefault treats it as a DateTime and therefore the required Field validators are getting attached, because the original expression is for a datetime not a nullable datetime.

    Therefore the solution below doesn't work.

    Like the asker, I also used the DateTimeModelBinder from here: Here's the Link

    This is how I solved a similar situation:

    @Html.EditorFor(x => x.NewAssignment.AssignmentEndDate.GetValueOrDefault().Date)
    

    And this is what my DateTime EditorTemplate looks like:

    @model DateTime
    
    @Html.TextBox("", Model != default(DateTime) ? Model.ToShortDateString() : String.Empty, new { @class = "datepicker", @maxlength = "10" })
    

提交回复
热议问题