Editorfor template complaining about data type, not sure how to solve

155 views Asked by At

I have a Product class:

public class Product
{
    [Key]
    public int ProductID { get; set; }

    [Required]
    public string Title { get; set; }

    [Required]
    [DataType(DataType.Date)]
    public DateTime ADate { get; set; }
}

When I go to create a product, obviously the fields are going to be empty but I still want to set my create.cshtml has type Product:

@model WebApplication.Domain.Entities.Product

So now this is done in my create.cshtml, I start to write the form for it and add an editor for my ADate property..

@Html.EditorFor(model => model.ADate, "DateTime" )

which in turn is using an editor template:

@model System.DateTime

@Html.TextBox(
   string.Empty, 
   Model.ToString("yyyy-MM-dd"),
   new { @class="datepicker", @type = "date"})

but when I do this, it complains on runtime:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'. 

What do I need to do in my

  • model,
  • create.cshtml or
  • DateTime.cshtml

to stop it complaining when the data is empty...

------------EDIT---------------

I ended up doing this in my DateTime.cshtml: does this look okay?

@model System.DateTime?

@if( Model.HasValue )
{ 
    @Html.TextBox(
        string.Empty, 
        Model.Value,
        new { @class="date", @type = "date"})
}
else
{ 
    @Html.TextBox(
        string.Empty, 
        null,
        new { @class="date", @type = "date"})
}
0

There are 0 answers