0
votes

I Have the following code in my Model

public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public DateTime DateAdded { get; set; }

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Number in Stock")]
    public byte NumberInStock { get; set; }

    public Genre Genre { get; set; }

    [Display(Name = "Genre")]
    [Required]
    public byte GenreId { get; set; }

This is my controller coder error point shows

[HttpPost]
    public ActionResult Create(Movie movie)
    {
        _context.Movies.Add(movie);
        _context.SaveChanges();

        return RedirectToAction("Index", "Movies");
    }

And this is the view

<div class="form-group">
    @Html.LabelFor(m => m.Movie.ReleaseDate)
    @Html.TextBoxFor(m => m.Movie.ReleaseDate, "{0:d MMM yyyy}", new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Movie.GenreId)
    @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Name"), "Select Movie Genre", new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Movie.NumberInStock)
    @Html.TextBoxFor(m => m.Movie.NumberInStock, new { @class = "form-control" })
</div>

<button type="submit" class="btn btn-primary">Save</button>

When I click submit button, I get an error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

Any idea about this problem? I'm assuming it's a datetime issue, but I cannot get the problem. I'm a beginner at this.

1
Make sure you use datetime2 rather than datetime; and if it's nullable, make sure the column is nullable.Richardissimo
its already nullable. But why i nedd datetime2? @RichardissimoCross
I gave a link with the explanation of why to use datetime2 rather than datetime...did you read it? Datetime2 has a wider range than datetime, preventing this out of range issue (alonng with several other good reasons.)Richardissimo

1 Answers

0
votes

The datetime column "DateAdded" is marked Not Nullable in sql.

Option 1 (change controller):

[HttpPost]
public ActionResult Create(Movie movie)
{
    //setdate
    movie.DateAdded = Datetime.Now;
    _context.Movies.Add(movie);
    _context.SaveChanges();

    return RedirectToAction("Index", "Movies");
}

Option 2 (change model)

public class Movie 
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public DateTime DateAdded { get; set; } = Datetime.Now;

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Number in Stock")]
    public byte NumberInStock { get; set; }

    public Genre Genre { get; set; }

    [Display(Name = "Genre")]
    [Required]
    public byte GenreId { get; set; }
}